LINQ Lambda-在一个列表中查找所有ID,而在另一个列表中不存在 [英] LINQ Lambda - Find all ID's in one list that don't exist in another list

查看:526
本文介绍了LINQ Lambda-在一个列表中查找所有ID,而在另一个列表中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象集合(列表list1和列表list2).每个称为"ID"的都有一个属性.我知道list2总是比list1拥有更多的项,我只需要一种简单的方法就可以使用LINQ lambda表达式来获取list2中存在的所有项的集合,而不是list1中存在的所有项的集合.

I have two collections of objects (List list1 and List list2). There is a property on each called "ID". I know that list2 will always have more items than list1, I just need an easy way to get a collection of all the items that exist in list2 but not list1 using LINQ lambda expressions.

推荐答案

如果您仅需要商品的ID,则

If you only need the IDs of the items then Mark's answer will do the trick nicely. If you need to return the items themselves (and they don't already have a suitable Equals implementation) then you could try something like this:

// assumes that the ID property is an int - change the generic type if it's not
var ids = new HashSet<int>(list1.Select(x => x.ID));
var results = list2.Where(x => !ids.Contains(x.ID));

这篇关于LINQ Lambda-在一个列表中查找所有ID,而在另一个列表中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆