使用 LINQ 通过一个属性比较两个列表 [英] Compare Two Lists Via One Property Using LINQ
问题描述
假设我有以下内容:
class Widget1{
public int TypeID { get; set; }
public string Color { get; set; }
}
class Widget2
{
public int TypeID { get; set; }
public string Brand { get; set; }
}
private void test()
{
List<Widget1> widgets1 = new List<Widget1>();
List<Widget2> widgets2 = new List<Widget2>();
List<Widget1> widgets1_in_widgets2 = new List<Widget1>();
//some code here to populate widgets1 and widgets2
foreach (Widget1 w1 in widgets1)
{
foreach (Widget2 w2 in widgets2)
{
if (w1.TypeID == w2.TypeID)
{
widgets1_in_widgets2.Add(w1);
}
}
}
}
我使用两个 foreach 循环按 TypeID 比较列表以填充第三个列表.有没有其他方法使用 LINQ 通过 TypeID 比较这两个列表?也许使用 Interstect 或其他一些函数?
I am using two foreach loops to compare the lists by TypeID to populate a third list. Is there any other way using LINQ to compare these two lists via the TypeID? Perhaps using Interstect or some other function?
推荐答案
你想要的是一个 Join
.
var widgets1_in_widgets2 = from first in widgest1
join second in widgets2
on first.TypeID equals second.TypeID
select first;
Intersect
可以或多或少地被认为是 Join
的一种特殊情况,其中两个序列的类型相同,因此可以应用于相等而不是需要为每种类型进行投影以生成要比较的键.鉴于您的情况,Intersect
不是一个选项.
Intersect
can be more or less thought of as a special case of Join
where the two sequences are of the same type, and can thus be applied for equality instead of needing a projection for each type to generate a key to compare. Given your case, Intersect
isn't an option.
如果特定 ID 在您的第二组中重复,并且您不希望该项目在结果中重复,那么您可以使用 GroupJoin
而不是 Join
>:
If a particular ID is duplicated in your second set and you don't want the item to be duplicated in the results then you can use a GroupJoin
instead of a Join
:
var widgets1_in_widgets2 = from first in widgest1
join second in widgets2
on first.TypeID equals second.TypeID
into matches
where matches.Any()
select first;
这篇关于使用 LINQ 通过一个属性比较两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!