C# 从列表中查找存在于另一个列表中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15769673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find items from a list which exist in another list
提问by donstack
I have a List<PropA>
我有一个 List<PropA>
PropA
{
int a;
int b;
}
and another List<PropX>
而另一个 List<PropX>
PropX
{
int a;
int b;
}
Now i have to find items from List<PropX>
which exist in List<PropA>
matching bproperty using lambda or LINQ.
现在我必须使用 lambda 或 LINQ找到匹配b属性中List<PropX>
存在的项目。List<PropA>
采纳答案by Servy
What you want to do is Join
the two sequences. LINQ has a Join
operator that does exactly that:
你想要做的是Join
两个序列。LINQ 有一个Join
运算符可以做到这一点:
List<PropX> first;
List<PropA> second;
var query = from firstItem in first
join secondItem in second
on firstItem.b equals secondItem.b
select firstItem;
Note that the Join
operator in LINQ is also written to perform this operation quite a bit more efficiently than the naive implementations that would do a linear search through the second collection for each item.
请注意,Join
LINQ中的运算符也被编写为执行此操作,这比在每个项目的第二个集合中进行线性搜索的简单实现要高效得多。
回答by Adrian Godong
ListA.Where(a => ListX.Any(x => x.b == a.b))
回答by Ambuj
回答by Sachin Prasad
Well all above will not work if you have multiple parameters, So I think this is the best way to do it.
如果您有多个参数,以上所有内容都不起作用,所以我认为这是最好的方法。
For example: Find not matched items from pets and pets2 .
例如:从 pets 和 pets2 中查找不匹配的项目。
var notMatchedpets = pets
.Where(p2 => !pets2
.Any(p1 => p1.Name == p2.Name && p1.age == p2.age))
.ToList();