Amr Ibrahim
Amr Ibrahim

Reputation: 177

Get the last record of group using LINQ

I have a list:

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}, 
};

I want to just get the latest record so the result would be like:

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

Upvotes: 5

Views: 9888

Answers (3)

Jubayer Hossain
Jubayer Hossain

Reputation: 89

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

It works for me...
So you can try.

Upvotes: 1

schlonzo
schlonzo

Reputation: 1406

Is this what you want to do?

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 }

Upvotes: 0

Chandan Rai
Chandan Rai

Reputation: 10359

Depending on what you want you can change OrderBy or even can use First or Last in this.

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

Upvotes: 11

Related Questions