使用LINQ合并对象列表 [英] Using LINQ to merge a list of objects

查看:45
本文介绍了使用LINQ合并对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象列表,我想使用Linq合并它们,但是在两个列表包含具有相同键的对象的情况下,我只想要具有最大LastUpdated值的对象.

I have two lists of objects, using Linq I would like to merge them, but where the two lists contain objects with the same key, I only want the one with the greatest LastUpdated Value.

我认为我可以以某种方式通过max(LastUpdated)的键a来获得列表分组,然后再加入到键和LastUpdated上的列表,但是必须有一种更有效的方法...

I thought that I could somehow get a list grouping by key a with max(LastUpdated) then join back to the list joining on key and LastUpdated, but there must be a more efficient way...

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;}
}

推荐答案

使用 MoreLINQ 中的DistinctBy a>:

var query = lstListA.Concat(lstListB)
                    .OrderByDescending(x => x.LastUpdated)
                    .DistinctBy(x => x.Key);

这篇关于使用LINQ合并对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆