8

我有 int[] 并想检查列表中的特定属性是否存在于数组中。这是我的财产类别,

public class WaitingLists
    {
        [Key]
        public Int32 Id { get; set; }
        public Guid UserId { get; set; }
        public Int32 GameTableId { get; set; }
        public Int32 WaitingListTypeId { get; set; }
        **public Int32 ? StakeBuyInId { get; set; }**
    }

然后我想检查我的列表中是否存在 StakeBuyInId。

这是Linq的代码,

public GameListItem[] GetMyWaitingList(Guid UserId, int[] WaitingListTypeIds, 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 (WaitingListTypeIds != null)
            {
                objWaitingListUser = objWaitingListUser.Where(x => WaitingListTypeIds.Contains(x.WaitingListTypeId));
            }
            **if (StakeBuyInIds != null)
            {
                objWaitingListUser = objWaitingListUser.Where(x => x.StakeBuyInId != null ? StakeBuyInIds.Contains(x.StakeBuyInId) : false);
            }**
            return objtempGameListItem.ToArray();
        }

但它向我显示了一个包含不允许 'int 的错误?'。它只会重载'int'。那么您知道如何使用 linq 将 Contains 用于 null 属性吗?谢谢你的帮助。

4

2 回答 2

6

尝试

StakeBuyInIds.Contains((Int32)x.StakeBuyInId)

或者

objWaitingListUser = objWaitingListUser.Where(x => 
                 x.StakeBuyInId.HasValue  && 
                 StakeBuyInIds.Contains((Int32)x.StakeBuyInId));
于 2013-06-14T06:05:32.307 回答
2

you could also create an extension

    public static bool Contains<T>(this IList<T> container, T? content)
    {
        if (content.HasValue)
            if (container.Contains(content.Value))
                return true;

        return false;
    }

and your query would looks like this

objWaitingListUser = objWaitingListUser.Where(x => StakeBuyInIds.Contains(x.StakeBuyInId))

instead of

objWaitingListUser = objWaitingListUser.Where(x => x.StakeBuyInId != null 
                                                   ? StakeBuyInIds.Contains(x.StakeBuyInId) 
                                                   : false);
于 2013-06-14T07:05:16.620 回答