Linq查询Sub / Group max两次

时间:2017-05-15 19:03:24

标签: c# linq

public class Event
{
    public int Id { get; set; }
    public string Emp { get; set; }
    public DateTime EventDate { get; set; }
    public DateTime AccessTime { get; set; }
}

var events = new List<Event>(){
    new Event(){Id=1,Emp ="A",EventDate= new DateTime(2017, 1, 2), AccessTime= DateTime.Now},
    new Event(){Id=2,Emp ="A",EventDate= new DateTime(2017, 1, 2), AccessTime= DateTime.Now.AddMinutes(4)},
    new Event(){Id=3,Emp ="A",EventDate= new DateTime(2017, 1, 2), AccessTime= DateTime.Now.AddMinutes(1)},
    new Event(){Id=4,Emp ="A",EventDate= new DateTime(2017, 1, 3), AccessTime= DateTime.Now},
    new Event(){Id=5,Emp ="A",EventDate= new DateTime(2017, 1, 3), AccessTime= DateTime.Now.AddMinutes(2)},
    new Event(){Id=6,Emp ="A",EventDate= new DateTime(2017, 1, 3), AccessTime= DateTime.Now.AddMinutes(3)},
    new Event(){Id=7,Emp ="B",EventDate= new DateTime(2017, 2, 2), AccessTime= DateTime.Now},
    new Event(){Id=8,Emp ="B",EventDate= new DateTime(2017, 2, 2), AccessTime= DateTime.Now.AddMinutes(1)},
    new Event(){Id=9,Emp ="B",EventDate= new DateTime(2017, 2, 2), AccessTime= DateTime.Now.AddMinutes(2)}
}; 

如何使用最新的EventDate和AccessTime获取Emps?首先,使用最新的EventDate获取项目。如果EventDates相同,则获取具有最新AccessTime的项目。对于此列表,结果应为事件6和9.

2 个答案:

答案 0 :(得分:0)

您要找的是OrderByThenBy。如果你的例子:

events.OrderByDescending(x => x.EventDate)
    .ThenByDescending(x => x.AccessTime);

这会先按最新events排序EventDate,然后按AccessTime排序(如果多个日期匹配)。

结果将包含ID 9,后跟8,因为它们具有最新的EventDate,而两个ID 9中的最新AccessTime

Dotnet Fiddle

答案 1 :(得分:0)

这会给你你想要的东西:

var result = events.GroupBy(x => x.Emp).Select(y => y.OrderByDescending(z => z.EventDate).ThenByDescending(q => q.AccessTime).First());
foreach (Event a in result)
{
            Console.WriteLine(a.Id + "\t" + a.Emp + "\t" + a.EventDate + "\t" + a.AccessTime);
}

首先,您需要Emp GroupBy,而不是OrderByDescending EventDate之前的订单组,而不是AccessTime和选择第一行。

最终结果将是:

  

9
  6