开发者

Linq expression to get all items in a IList where one field is in another List

开发者 https://www.devze.com 2023-04-07 00:25 出处:网络
This collection contains the entire database of products: IList<Products> allProducts; This contains just the guids of all the products for this user:

This collection contains the entire database of products:

IList<Products> allProducts;

This contains just the guids of all the products for this user:

ILis开发者_开发百科t<Guid> usersProducts;

Below is the psuedo code of what I need, i.e. all the product classes in a IList for a given user and the product is also of type == 1.

var filteredProducts = (p from allProducts
                       where p.Id in usersProducts && p.Type == 1).List();

I can't figure out how to do the SQL query "WHERE IN (..., ...,)


var filteredProducts = (from p in allProducts
                            where usersProducts.Contains(p.Id) && p.Type == 1
                            select p).ToList();


@Samich's answer is correct. It's just a personal preference, but I prefer the method syntax...

var filteredProducts = allProducts.Where(p => p.Type == 1 && userProducts.Contains(p.Id)).ToList();

Also, for performance reasons, I swapped the order of your conditionals. If p.Type doesn't equal 1, the Contains won't execute.


Sounds like you just want a join.

var filteredProducts = (from p in allProducts 
                       join u in usersProducts on p.Id equals u.Id
                       where p.Type == 1
                       select p).ToList();
0

精彩评论

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