Iti Tyagi
Iti Tyagi

Reputation: 3661

Group by in Linq to get further details

I have table data as:

Fname   Lname   Date          ForeignKey
 A       B      2012-01-01      1
 A       B      2012-11-01      1
 A       B      2013-12-25      1
 C       K      2009-01-01      2
 C       K      2001-11-01      2
 C       K      2011-12-25      2

My table is referred as ABC in EF So I want to group them by Foreign Key, and I am able to do that by using this query, but How to get the details of each row now?

var q =  from abc in context.ABC
         group abc by abc.ForeignKey into g
         join efg in context.EFG on g.Key equals efg.AppId
         select new
         {
             MortgId = g.Key,
             TrackingDate = g.Max(val => val.Date),
             Fname=g.?,
             Lname=g.?,
             Sale=efg.SalesAmount
         };
        foreach(var result in q)
        {
         if(result.Fname=="A")
         {
         }
        }

It returns me the list. This gives me the Record of maximum date but I want to get the details of Fname and Lname of this Maximum Date and I am not able to get any clue.

UPDATE: The result should be like this:

Fname   Lname   Date          ForeignKey
 A       B      2013-12-25      1
 C       K      2011-12-25      2

I want to get the details against the maximum date.
NEW UPDATE: So I want to check on the basis of Fname and I have made a question mark that how to get the Fname of the maximum date result. I hope it is clear now.

Upvotes: 0

Views: 608

Answers (1)

cuongle
cuongle

Reputation: 75306

Get object which has max date for each group by ordering by descending, and get first:

var list = context.ABC.GroupBy(abc => abc.ForeignKey)
        .Select(g => g.OrderByDescending(a => a.Date).First())

Then you can get other properties easily:

foreach (var abc in list)
{
    var fname = abc.Fname;
    var lname = abc.Lname;
}

Upvotes: 1

Related Questions