4

我在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[] 有时会为空,那么我将如何对上述 sql 查询执行 linq 操作。谢谢你的帮助。

4

2 回答 2

1

您可能只检查表达式之外的 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。

于 2013-06-15T05:24:32.437 回答
0

waitingListTypeIdandstakeBuyinId应该在你的nullable int关系对象WaitingList中。

List<int?> WaitingListTypeIds=new List(new int?[]{1});
    var StakeBuyInIds=from w in WaitingListsCollection where new List<int?>(new int?[]{5}).Contains(w.StakeBuyInId) && w.WaitingListTypeId = 2;
        var output= from w in WaitingListsCollection where  WaitingListTypeIds.Contains(w.WaitingListTypeId) || StakeBuyInIds.Contains(w.StakebuyInId)
于 2013-06-15T05:49:48.327 回答