如何在给定属性上合并两个列表 [英] How to merge two lists on a given property
问题描述
我有两个查询,每个查询返回一个对象列表.
I have two queries, each one returning a list of objects.
List<A> list1 = (....query...)
List<A> list2 = (....query...)
"A"是一个对象模型.
"A" is an object model.
两个查询都返回几乎相同的对象,但设置了不同的属性.
Both queries return almost the same objects but with different properties set.
我要删除重复项,并根据对象A的属性将其合并为一个列表.
I want to remove duplicates merge them into a single list based on a property of object A.
基本上是这样的:
List<A> finalLis = list1 join list2 on elemList1.somePropID == elemList2.somePropID
在简单的C#风格中,将是这样的:
In simple C# style it would be something like this:
foreach(elem1 : list1) {
foreach(elem2: list1) {
if(elem1.someID == elem2.someID) {
elem1.someProp = elem2.someProp
elem1.otherProp = elem2.otherProp
}
}
}
我不想这样做,因为我确信linq中有一种更优雅的方法.
I don't want to do it in this way because I'm sure there's a more elegant way in linq.
如果您有任何建议,请告诉我.
If you have any suggestions please let me know.
推荐答案
Linq可以帮助您进行选择,但不能帮助您进行更新.因此,您不会摆脱foreach
语句.因此,您的任务可以像这样用linq编写:
Linq can help you with selecting but not with updating. So you won't get rid of foreach
statement. So your task could be written with linq like this:
//the query is like LEFT JOIN in SQL
var query = from x in list1
join y in list2 on x.IDItem equals y.IDItem
into z
from q in z.DefaultIfEmpty()
select new {IOne = x, ITwo = q};
foreach (var pair in query)
{
if (pair.ITwo != null) // && pair.IOne.OneProperty != null
pair.IOne.OneProperty = pair.ITwo.TwoProperty;
}
var resultList = query.Select(x => x.IOne).ToList();
您可以在此处查看结果.
这篇关于如何在给定属性上合并两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!