Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Entity lambda, group by some columns and select more columns

My logic went like this :

db.table.GroupBy(t => new { t.A, t.B}).Select( t => new { t.A, t.B, t.C, t.D});

At first, i thought Distinct() would help... but absolutely not.

See... i want to take only the different combinations of A and B but select A, B, C, D.

Upvotes: 0

Views: 580

Answers (1)

juharr
juharr

Reputation: 32266

To get the unique combination of A and B you just get them from the Key property, then you have to decide which C and D values you want. Here I'm just pulling them from the first row for each A - B combination, but you can do other aggregations like Min, Max, or Average.

db.table.GroupBy(t => new {t.A, t.B})
    .Select(g => new {g.Key.A, g.Key.B, g.First().C, g.First().D});

The trick is to understand that GroupBy gives you a IEnumerable<IGrouping<TKey, TResult>> and IGrouping<TKey, TResult> is an IEnumerable<TResult> and has a Key property of type TKey. So the lambda you use in your Select is dealing with something that has a Key based on what you grouped on and is a collection of all the items/rows that are grouped for that unique key value.

Upvotes: 3

Related Questions