如何在linq c#中编写下面的sql查询,其中一些paramteres有时会为null

我在sql中有以下查询,

select * from dbo.WaitingLists 
where WaitingListTypeId in (1)
or StakeBuyInId in (Select StakeBuyInId from dbo.WaitingLists where StakeBuyInId in (5) and 
WaitingListTypeId = 2)

在此,有时StakeBuyInId将为null或WaitingListTypeId将为null.我想在以下代码中通过linq c#执行此查询.

public GameListItem[] GetMyWaitingList(Guid UserId,int LocalWaitingListTypeId,int GlobalWaitingListTypeId,int[] StakeBuyInIds)
            {
                ProviderDB db = new ProviderDB();

                List<GameListItem> objtempGameListItem = new List<GameListItem>();

                List<GaMetables> objGaMetablesList = new List<GaMetables>();

                var objWaitingListUser = db.WaitingLists.Where(x => x.UserId.Equals(UserId));

                if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
                {
                    objWaitingListUser = objWaitingListUser.Where(x => x.WaitingListTypeId == LocalWaitingListTypeId || (x.WaitingListTypeId == GlobalWaitingListTypeId 
                                            && StakeBuyInIds != null ? StakeBuyInIds.Contains((Int32)x.StakeBuyInId) : true)
                                         );
                }
                return objtempGameListItem.ToArray();
            }

这里StakeBuyInIds int []有时会为null,那么我将如何对上面的SQL查询执行linq操作.谢谢你的帮助.

解决方法

您可以在表达式之外检查null,如下所示:

if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
{
    if (StakeBuyInIds != null)
    {
        objWaitingListUser = objWaitingListUser.Where(
            x => x.WaitingListTypeId == LocalWaitingListTypeId || 
                 (x.WaitingListTypeId == GlobalWaitingListTypeId && 
                  StakeBuyInIds.Contains((Int32)x.StakeBuyInId));
    } else {
        objWaitingListUser = objWaitingListUser.Where(
            x => x.WaitingListTypeId == LocalWaitingListTypeId || 
                 x.WaitingListTypeId == GlobalWaitingListTypeId);
    }
}

您也可以这样做:

if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
{
    var arrayNull = StakeBuyInIds != null;
    var array = StakeBuyInIds ?? new int[0];
    objWaitingListUser = objWaitingListUser.Where(
        x => x.WaitingListTypeId == LocalWaitingListTypeId || 
             (x.WaitingListTypeId == GlobalWaitingListTypeId && 
              (arrayNotNull || array.Contains((Int32)x.StakeBuyInId)));
}

它会影响它在查询之外测试null,但确保在实际执行查询时它不能为null.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...