C#Linq查询:从列表中获取键在其他列表中的所有项目

C#Linq查询:从列表中获取键在其他列表中的所有项目

问题描述:

我有两个列表集合.一个带有键,另一个带有记录.

I have two list collections. One with keys and one with records.

class Record
{
int key;
string Data;
}

List<int> Keys = new List<int>{1,2,3};

List<record> records = [SOME_RECORDS]
</record></int></int>



如何从记录"列表中获取所有项,其中键"列表中的键属性是什么?



How to get all items from Records list which key property is in Keys list?
Could it be one line linq expression?

使用您的代码,我会这样做:

Using your code, I''d do it like this:

var results = records.Where(r => Keys.Contains(r.key));


或者您也可以通过联接来执行此操作,以防添加更多条件,例如:
Or you can also do this with a join in case you want to add more conditions etc:
var query = from record in records
            join key in Keys on record.key equals key
            select record;

如果同一条记录可以有多个键,则可以使用Distinct操作

In case you can have multiple keys for the same record, you can use the Distinct operation