代码之家  ›  专栏  ›  技术社区  ›  user584018

如何获得每个item2和item3组合的最大日期时间?

  •  0
  • user584018  · 技术社区  · 4 年前

    我有这样一个元组中来自外部系统的数据,有很多item2和item3的组合,具有不同的datetime。

    var data = new List<Tuple<DateTime, string, string>>
            {
                new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 5, 10, 20), "A1", "X1"),
                new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 6, 10, 22), "A1", "X1"),
                new Tuple<DateTime, string, string>(new DateTime(2021, 04, 02, 7, 11, 21), "A2", "X2")
            };
    

    现在我需要针对每个唯一的item2和item3组合获取MAX datetime,返回的结果应该是这样的,

    var result = new List<Tuple<DateTime, string, string>>
            {
                new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 6, 10, 22), "A1", "X1"),
                new Tuple<DateTime, string, string>(new DateTime(2021, 04, 02, 7, 11, 21), "A2", "X2")
            };
    

    我能够获取每个item2和item3组合的MAX datetime,其中我将这些值作为硬代码传递,

     var maxTimestamp = data.Where(t => t.Item2 == "A1" && t.Item3 == "X1").Max(t => t.Item1);
    

    但是我需要迭代每一个item2和item3的组合,如何做到这一点?

    1 回复  |  直到 4 年前
        1
  •  1
  •   SomeBody    4 年前

    使用 GroupBy

    var maxTimestamps = data.GroupBy(x => new { x.Item2, x.Item3}).
                             Select(x => x.OrderByDescending(y => y.Item1).First());
    

    您将得到具有相同属性的组 Item2 Item3 . 按日期对这些组进行排序,并选择每个组的第一个日期。