c# - 如何在 linq c# 中编写下面的 sql 查询,其中某些参数有时会为 null

标签 c# linq sql-server-2008

我在 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。

关于c# - 如何在 linq c# 中编写下面的 sql 查询,其中某些参数有时会为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17120432/

相关文章:

c# - SQL Server 和 C# 的输出不同

c# - 推送通知不使用 Azure 从控制台发送

c# - 如何在我的属性中设置动态值

c# - LinqToXml 还是 Xml?

c# - LINQ 语句中的多个 OR 子句

linq - 在LINQ中学习表达式树

c# - Entity Framework 中的构造函数初始化

c# - 为什么 LINQ 不是纯函数式的?

sql - 限制行数 - TSQL - 合并 - SQL Server 2008

sql - 无法在表中插入新列