Brucelin Michael
Brucelin Michael

Reputation: 513

How to use Linq's lambda expression to query both aggregate and detail values

var query = from i in listModel
group i by new { i.ClassId, i.Gender } into g
orderby g.Key.ClassId, g.Key.Gender
from item in g
select new
{
    g.Key.ClassId,
    g.Key.Gender,
    item.Name,
    Count = g.Count(),
    MaxAge = g.Max(i => i.Age),
    MinAge = g.Min(i => i.Age)
};

Using this code, I can find out the aggregated value (Count, MaxAge, MinAge) and the detailed value (Name) before grouping at the same time. How can the above statement be implemented by Linq's Lambda expression?

Upvotes: 0

Views: 207

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

Try the conjunction of GroupBy, OrderBy and SelectMany extension methods

var query = listModel.GroupBy(i => new { i.ClassId, i.Gender })
    .OrderBy(g => g.Key.ClassId)
    .ThenBy(g => g.Key.Gender)
    .SelectMany(g => g, (g, item) => new
    {
        g.Key.ClassId,
        g.Key.Gender,
        item.Name,
        Count = g.Count(),
        MaxAge = g.Max(i => i.Age),
        MinAge = g.Min(i => i.Age)
    });

Upvotes: 1

Related Questions