【问题标题】:Linq to select objects with unique Id and greatest date?Linq 选择具有唯一 ID 和最大日期的对象?
【发布时间】:2018-10-05 01:03:46
【问题描述】:

我有一个如下所示的对象列表:

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

我的数据如下所示:

 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

如何进行 linq 查询以在列表中返回这 2 个,在该列表中它获取版本号为 1 的最大日期的项目,并且还使用 TypeId 返回更多项目?

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

这是我尝试过的,但由于我的 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();

【问题讨论】:

  • also uses the TypeId to return more items?是什么意思

标签: c# .net linq


【解决方案1】:

您需要按 typeId 分组,然后在每个组中按日期排序元素。然后您可以选择每个组中的第一个元素。试试这个代码:

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多