C# 两个列表对象之间的 Linq 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9021618/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:37:28  来源:igfitidea点击:

Linq query between two list objects

c#linq

提问by Reno

I have two objects:

我有两个对象:

ObjectA
{
   string code;
   string country;
}

ObjectB
{
   string code;
   string otherstuff;
}

And I have List<objectA>and List<ObjectB>and I need to find all objects in List<ObjectB>which contains objectA.Code. But cannot manage to implement it on LINQ query.

我有List<objectA>并且List<ObjectB>我需要找到所有List<ObjectB>包含objectA.Code. 但是无法在 LINQ 查询上实现它。

采纳答案by JaredPar

It sounds like you are trying to find all instances of ObjectBwhich have a codevalue present in any of the List<ObjectA>values. If so try the following

这听起来像你正在努力寻找的所有实例ObjectB其中有一个code存在于任何的价值List<ObjectA>值。如果是这样,请尝试以下操作

List<ObjectA> listA = ...;
List<ObjectB> listB = ...;
var all = listB.Where(b => listA.Any(a => a.code == b.code));

回答by BrokenGlass

To do this effectively you can first put the codes into a HashSet<string>and then use a Contains()query to check if the B in question has a code that is contained in the hashset:

要有效地做到这一点,您可以首先将代码放入 a 中HashSet<string>,然后使用Contains()查询来检查有问题的 B 是否具有包含在哈希集中的代码:

var codes = new HashSet<string>(listOfAs.Select(x => x.code));
var selectedBs = listOfBs.Where( x=> codes.Contains(x.code));

回答by jeroenh

It sounds like you want to join the list of ObjectA with the list of ObjectB on the codeproperty. This is one way:

听起来您想将 ObjectA 的列表与code属性上的 ObjectB 列表连接起来。这是一种方式:

List<ObjectA> listOfA = ...;
List<ObjectB> listOfB = ...;
var all = from a in listOfA
          join b in listOfB on a.code equals b.code
          select new {a,b};

The result is a list of anonymous objects, containing 2 properties: a of type ObjectA, b of type ObjectB, with the same code

结果是一个匿名对象列表,包含 2 个属性:a 类型 ObjectA,b 类型 ObjectB,具有相同的 code

回答by Olivier Jacot-Descombes

I would put the codes of the ObjectAlist into a HashSet, otherwise your query would become an O(n2) operation. Like this it is an O(n) operation:

我会将ObjectA列表的代码放入 HashSet 中,否则您的查询将变成 O(n 2) 操作。像这样它是一个 O(n) 操作:

var aList = new List<ObjectA>();
var bList = new List<ObjectB>();

var aCodes = new HashSet<string>(aList.Select(a => a.code));
var result = bList.Where(b => aCodes.Contains(b.code));