简体   繁体   English

Linq查询以基于日期排序列表并获得不同

[英]Linq query to order a list based on date and get distinct

I have a list as shown below: 我有一个列表,如下所示:

List<MyObjects> list:
list[0] - Id: 1; RefId:101; Date:22/06/2016
list[1] - Id: 2; RefId:102; Date:24/06/2016
list[2] - Id: 3; RefId:101; Date:26/06/2016
list[3] - Id: 4; RefId:103; Date:28/06/2016

I need a linq query,which gets me distinct based on RefId having latest date, something like this: 我需要一个linq查询,它基于具有最新日期的RefId来使我与众不同,如下所示:

List<MyObjects> newList:
list[0] - Id: 3; RefId:101; Date:26/06/2016
list[1] - Id: 2; RefId:102; Date:24/06/2016
list[2] - Id: 4; RefId:103; Date:28/06/2016

Here RefId-101 is repeated but its first date value is old, hence removed. 在此重复RefId-101,但其第一个日期值较旧,因此将其删除。 Thanks in advance. 提前致谢。

Using Linq Group by RefId then order each group by Date then take first out of each group : 使用Linq按RefId分组,然后按Date对每个分组排序,然后从每个分组中取出第一个:

list.GroupBy(x => x.RefId).Select(x => x.OrderByDescending(y => y.Date).FirstOrDefault());

OR using Query-Syntax: 或使用查询语法:

List<MyObjects> results = (from x in list
                            group x by x.RefId into grp
                            select grp.OrderByDescending(y => y.Date).FirstOrDefault()
                            ).ToList();

You can use GroupBy to group by RefId , then sort this groups by Date and take the first ones: 您可以使用GroupByRefId进行分组,然后按Date对这些分组进行排序,并采用第一个分组:

var result = list.GroupBy(o => o.RefId)
      .Select(g => g.OrderByDescending(gx => gx.Date).First())
      .ToList();

Since you want the latest Date , you need to OrderByDescending . 由于您需要最新的 Date ,因此需要OrderByDescending

I think it is best to avoid calling .FirstOrDefault() . 我认为最好避免调用.FirstOrDefault() Here's an alternative: 这是一个替代方案:

var newList =
    list
        .GroupBy(x => x.RefId)
        .SelectMany(x => x.OrderByDescending(y => y.Date).Take(1))
        .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM