LINQ:在和另一个列表中匹配任何名称(字符串)列表中返回的项目吗? [英] LINQ: return items in a List that matches any Names (string) in another list?
问题描述
我有2列出。图1是产品的集合。另一种是产品在商店的集合。
我需要能够返回所有shopProducts如果名称中的产品匹配任何名称。
我有这个,但它似乎并没有工作。任何想法?
VAR产品= shopProducts.Where(P => p.Name.Any(listOfProducts。
选择(L => l.Name)。.ToList()))了ToList();
我不吐不快其中名称中的其他列表中存在给我所有的shopproducts。
任何帮助真的AP preciated
感谢
VAR产品= shopProducts.Where(P => listOfProducts.Any(L => p.Name == l.Name))
.ToList();
有关LINQ到对象,如果 listOfProducts
包含很多项目,那么你的可能的,如果你创建一个 HashSet的< T>
包含所有需要的名,然后使用在您的查询。 的HashSet< T>
为O(1)查找性能相比O(n)的一个任意的IEnumerable< T>
VAR名=新的HashSet<串GT;(listOfProducts.Select(P => p.Name));
变种产品= shopProducts.Where(P => names.Contains(p.Name))
.ToList();
有关LINQ到SQL,我希望(希望?)的提供者可以自动优化生成的SQL而不需要查询的任何手动调整。
I have 2 lists. 1 is a collection of products. And the other is a collection of products in a shop.
I need to be able to return All shopProducts if the names match any Names in the products.
I have this but it doesn't seem to work. Any ideas?
var products = shopProducts.Where(p => p.Name.Any(listOfProducts.
Select(l => l.Name).ToList())).ToList();
I really need to say give me all the shopproducts where name exists in the other list.
Any help really appreciated
Thanks
var products = shopProducts.Where(p => listOfProducts.Any(l => p.Name == l.Name))
.ToList();
For LINQ-to-Objects, if listOfProducts
contains many items then you might get better performance if you create a HashSet<T>
containing all the required names and then use that in your query. HashSet<T>
has O(1) lookup performance compared to O(n) for an arbitrary IEnumerable<T>
.
var names = new HashSet<string>(listOfProducts.Select(p => p.Name));
var products = shopProducts.Where(p => names.Contains(p.Name))
.ToList();
For LINQ-to-SQL, I would expect (hope?) that the provider could optimise the generated SQL automatically without needing any manual tweaking of the query.
这篇关于LINQ:在和另一个列表中匹配任何名称(字符串)列表中返回的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!