MadNeox
MadNeox

Reputation: 2485

Linq Grouping the result of group by query

I have the following exemple :

Model mod1 = new Model {  Header = "A", canDelete = true,pax=1 };
Model mod2 = new Model {  Header = "B", canDelete = true,pax=1 };
Model mod3 = new Model {  Header = "A", canDelete = true,pax=2 };
Model mod4 = new Model {  Header = "B", canDelete = false,pax=2 };
Model mod5 = new Model {  Header = "A", canDelete = true,pax=3 };
Model mod6 = new Model {  Header = "B", canDelete = false,pax=3 };
Model mod7 = new Model {  Header = "A", canDelete = false,pax=4 };
Model mod8 = new Model {  Header = "B", canDelete = true,pax=4 };

I added these models to a listMod

I want to group first by pax number, so I used :

var resultQuery = listMod.GroupBy(p=>p.pax);

How can I re-group the result of my resultQuery by Header and canDelete ?

The aim is to have 3 groups :

1st group : mod1 and mod2
2nd group : mod3 , mod4 , mod5 and mod6
3rd group : mod7 and mod8

Upvotes: 2

Views: 1159

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

Well, there may be a better way, but this one should work, assuming you have always two items for each pax number.

The "trick" is to concatenate the first and second canDelete / Header pair of items grouped by pax, and to group on that value.

Than the list inside the groups are flattened (using SelectMany)

listMod.GroupBy(m => m.pax)
    .Select(m => new
            {
                 valuePair = string.Format("{0}-{1}/{2}-{3}", m.First().canDelete, m.First().Header, m.Last().canDelete, m.Last().Header),
                 value = m.Select(x => x)
            })
    .GroupBy(m => m.valuePair)
    .Select(g => g.SelectMany(x => x.value))
    //.ToList();

if you wanna avoid this bad concatenation, you can also do

var result = listMod
                 .GroupBy(m => m.pax)
                 .Select(m => new
                 {
                      a1 = m.First().canDelete,
                      a2 = m.First().Header,
                      b1 = m.Last().canDelete,
                      b2 = m.Last().Header,
                      value = m.Select(x => x)
                  })
                  .GroupBy(m => new {m.a1, m.a2, m.b1, m.b2})
                  .Select(g => g.SelectMany(x => x.value))
                  //.ToList();

Upvotes: 1

Related Questions