开发者

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

开发者 https://www.devze.com 2023-02-02 15:58 出处:网络
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 开

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

精彩评论

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

关注公众号