简体   繁体   English

Linq选择具有唯一ID和最大日期的对象?

[英]Linq to select objects with unique Id and greatest date?

I have a list of objects that look like this: 我有一个看起来像这样的对象列表:

public class A
{
    public int Id {get; set;}
    public DateTime Date {get;set;}
    public int TypeId {get; set;}
    public int Version {get; set;}
}

My data looks like this: 我的数据如下所示:

 Id    Date     TypeId   Version
 1     10/3/18    1        1
 2     10/3/18    1        2
 3     10/4/18    1        1
 4     10/4/18    2        1

How can I make a linq query to return these 2 in a list where it gets the item with the greatest date where the version # is 1 and also uses the TypeId to return more items? 如何进行linq查询以在列表中返回这2个项,从而在列表中获取日期最大的项(版本号为1),并使用TypeId返回更多项?

 Id    Date     TypeId   Version
 3     10/4/18    1        1
 4     10/4/18    2        1

This is what I have tried but my code only returns one item because of my FirstOrDefault function. 这是我尝试过的方法,但是由于FirstOrDefault函数,我的代码仅返回一项。

        var q = from n in A.All.Where(x => x.Version == 1)
                group n by n.TypeId into g
                select g.OrderByDescending(t => t.Date).FirstOrDefault();

You need to group by typeId and then in each group order elements by date. 您需要按typeId分组,然后在每个分组中按日期对元素进行排序。 Then you can pick first element in each group. 然后,您可以在每个组中选择第一个元素。 Try this code: 试试这个代码:

var input = new[]
{
    new A {Id = 1, Date = new DateTime(2018, 10, 3), TypeId = 1, Version = 1},
    new A {Id = 2, Date = new DateTime(2018, 10, 3), TypeId = 1, Version = 2},
    new A {Id = 3, Date = new DateTime(2018, 10, 4), TypeId = 1, Version = 1},
    new A {Id = 4, Date = new DateTime(2018, 10, 4), TypeId = 2, Version = 1},
};

var result = input.Where(a => a.Version == 1)
    .GroupBy(a => a.TypeId)
    .Select(g => g.OrderByDescending(x => x.Date).First())
    .ToArray();

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

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