使用LINQ获取组的最后一条记录

时间:2017-02-17 14:08:15

标签: c# linq linq-to-sql

我有一个清单:

var list = new List<Foo>() {
     new Foo() { FooId = 1, GroupId = 1, ValueA = 3}, 
     new Foo() { FooId = 2,GroupId = 1, ValueA = 40}, 
     new Foo() { FooId = 3,GroupId = 2, ValueA = 80}, 
     new Foo() { FooId = 4, GroupId = 2, ValueA = 20}, 
};

我想获得最新记录,结果如下:

| GroupId | ValueA |
|---------|--------|
|     1   |   40   | 
|     2   |   20   |

3 个答案:

答案 0 :(得分:2)

根据您的需要,您可以更改OrderBy,甚至可以使用FirstLast

list
  .OrderByDescending(a => a.ValueA)
  .GroupBy(a => a.GroupId)
  .Select(g => g.Last());

答案 1 :(得分:1)

var result = 
    ( from   p in List
      group  p by p.Value into g
      select new { 
        GroupId = g.OrderByDescending(x=>x.Id).FirstOrDefault().GroupId,
        ValueA = g.OrderByDescending(x => x.Id).FirstOrDefault().ValueA 
      }
    ).ToList();

对我有用...
所以您可以尝试。

答案 2 :(得分:0)

这是你想要做的吗?

var result1 = from p in list
    group p by p.GroupId into g
    select new { GroupId = g.Key, MaxFooId = g.FooId.Max() };

var result2 = from p in result1
    join list q on p.MaxFooId equals q.FooId
    select new { GroupId = p.GroupId, ValueA = q.ValueA }