从列表中查找另一个列表中存在的项目 [英] Find items from a list which exist in another list

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

问题描述

我有一个List<PropA>

PropA  
{  
    int a;  
    int b;  
}

和另一个List<PropX>

PropX  
{  
    int a;  
    int b;  
}

现在,我必须使用lambda或LINQ从List<PropX>中找到与 b 属性匹配的List<PropA>中存在的项目.

Now i have to find items from List<PropX> which exist in List<PropA> matching b property using lambda or LINQ.

推荐答案

您要做的是Join这两个序列. LINQ有一个Join运算符可以做到这一点:

What you want to do is Join the two sequences. LINQ has a Join operator that does exactly that:

List<PropX> first;
List<PropA> second;

var query = from firstItem in first
    join secondItem in second
    on firstItem.b equals secondItem.b
    select firstItem;

请注意,LINQ中的Join运算符也被编写为比朴素的实现要高效得多,该朴素的实现将对每个项目的第二个集合进行线性搜索.

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.

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

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