C#Linq查询:从列表中获取键在其他列表中的所有项目 [英] C# Linq query: Get all items from list which key is in other list

查看:92
本文介绍了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


这篇关于C#Linq查询:从列表中获取键在其他列表中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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