我在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))); }