比较两份名单通过一个物业使用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 to通过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?
推荐答案
您想在这里什么是加入
。
var widgets1_in_widgets2 = from first in widgest1
join second in widgets2
on first.TypeID equals second.TypeID
select first;
相交
可以是更多或想象的那样作为一个特例加入
其中两个序列是相同类型的,并且因此可以应用于平等代替需要一个突起的每种类型,以产生一个关键来比较。鉴于你的情况下,相交
不是一个选项。
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在你的第二组和复制你不想要的项目在结果被复制,那么你可以使用,而不是一个群组加入
A 加入
:
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屋!