LINQ return items in a List that matches any Names (string) in another list(LINQ 返回列表中与另一个列表中的任何名称(字符串)匹配的项目)
问题描述
我有 2 个列表.1是产品的集合.另一个是商店中的产品集合.
I have 2 lists. 1 is a collection of products. And the other is a collection of products in a shop.
如果名称与产品中的任何名称匹配,我需要能够返回所有 shopProducts.
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 need to say give me all the shopproducts where name exists in the other list.
推荐答案
var products = shopProducts.Where(p => listOfProducts.Any(l => p.Name == l.Name))
.ToList();
对于 LINQ-to-Objects,如果 listOfProducts
包含许多项目,那么如果您创建一个 HashSet
,您可能会获得更好的性能包含所有必需的名称,然后在您的查询中使用它.HashSet
与任意 IEnumerable
的 O(n) 相比,具有 O(1) 的查找性能.
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();
对于 LINQ-to-SQL,我希望(希望?)提供程序可以自动优化生成的 SQL,而无需对查询进行任何手动调整.
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 返回列表中与另一个列表中的任何名称(字符串)匹配的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ 返回列表中与另一个列表中的任何名称(字符


基础教程推荐
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01