开发者

Linq intersect a child list of integers against a list of integers

I have a list of users each of which contains a list of associated storefront IDs. I have a separate list of integers and I want to find where any storefront id of a user matches any of the integers 开发者_Go百科in the separate list.

I'm expecting something like this:

clientUsers = clientUsers.Where(x => x.Storefronts.Intersect(allowedStorefrontIds));

I'm told the type arguments can't be inferred from the usage on the Where extension method.

Do you know how I should structure my linq in this case?


You just need a .Any() in the lambda to check if the set-intersection contains any elements:

x => x.Storefronts.Intersect(allowedStorefrontIds).Any()

Personally, I would do something like this for efficiency:

var allowedIds = new HashSet<int>(allowedStorefrontIds);

var allowedUsers = clientUsers.Where(x => x.StoreFronts.Any(allowedIds.Contains));


Where expects a function that returns a boolean expression. Intersect returns a list. I think clientUsers.Intersect(allowedStorefrontIds) should return the list you're expecting, unless there is another list not mentioned in the code snippet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜