什么是“现代”?在两个 List中查找共同项的方法物体?
我有两个包含不同类型的通用列表,为了举例,我们将它们称为 Products
和 Employees
。我正在尝试查找与员工位于同一位置的产品,即其中 product.SiteId == emp.SiteId
List<Product> lstProds;
List<Employees> lstEmps;
我的(old skool)大脑告诉我使用 forEach
循环来查找匹配项,但我怀疑有一种(“更好”/terser/更快?)方法可以使用 Linq 来完成此操作。谁能照亮我吗?我在网上找到的所有示例都涉及基元列表(字符串/整数),并且并不是特别有用。
I have two Generic Lists containing different types, for the sake of example, lets call them Products
and Employees
. I'm trying to find Products that are based at the same location as Employees, i.e. where product.SiteId == emp.SiteId
List<Product> lstProds;
List<Employees> lstEmps;
My (old skool) brain is telling me to use a forEach
loop to find the matches but I suspect there is a ('better'/terser/faster?) way to do it using Linq. Can anyone illuminate me? All the examples I've found online deal with Lists of primitives (strings/ints) and are not especially helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会说:
但是,如果有多个员工具有相同的站点 ID,您将多次获得产品。您可以使用
Distinct
来解决此问题,或者构建一组站点 ID:假设
SiteId
是int
- 如果它是匿名类型或类似的东西,您可能需要一个额外的扩展方法:然后:
或者,如果您的员工很少,这会起作用,但相对较慢:
向这些方法中的任何一个添加
ToList
调用以获得List
而不是IEnumerable
。I would say:
However, if there are multiple employees with the same site ID, you'll get the products multiple times. You could use
Distinct
to fix this, or build a set of site IDs:That's assuming
SiteId
is anint
- if it's an anonymous type or something similar, you may want an extra extension method:Then:
Alternatively, if you have few employees, this will work but is relatively slow:
Add a
ToList
call to any of these approaches to get aList<Product>
instead of anIEnumerable<Product>
.