我有两个对象列表,使用Linq我想合并它们,但是当两个列表包含具有相同键的对象时,我只想要具有最大LastUpdated值的那个。
我认为我可以通过键a a(LastUpdated)以某种方式获得列表分组,然后加入返回加入key和LastUpdated的列表,但必须有更有效的方式......
List<MyObject> lstListA = new List<MyObject>;
List<MyObject> lstListB = new List<MyObject>;
public class MyObject
{
public string Key {get;set;}
public string Value {get;set;}
public DateTime LastUpdated {get;set;}
}
答案 0 :(得分:17)
一种选择,使用MoreLINQ中的DistinctBy
:
var query = lstListA.Concat(lstListB)
.OrderByDescending(x => x.LastUpdated)
.DistinctBy(x => x.Key);
答案 1 :(得分:2)
经典选秀权。
IEnumerable<MyObject> query = lstListA
.Concat(lstListB)
.GroupBy(x => x.Key)
//now work with each group to pick a winner
.Select(g => g.OrderByDescending(x => x.LastUpdated).First())
答案 2 :(得分:0)
有点卷曲,但这似乎也有效:
var mergedItems = lstListA.Concat(lstListB);
mergedItems =
(from item in mergedItems
group item by item.Key into grp
let sameKey = mergedItems.Where(obj => obj.Key == grp.Key)
select sameKey.Where(obj => obj.LastUpdated == grp.Max(obj2 => obj2.LastUpdated)).Single()
).ToList();