Home > Software design >  Linq GroupBy Max within Max
Linq GroupBy Max within Max

Time:10-29

    var list = new[]
        {
            new { maker="Volvo", type=1, model=15},
            new { maker="Volvo", type=8, model=10},
            new { maker="Volvo", type=8, model=100},
            new { maker="Volvo", type=8, model=40},
            new { maker="Volvo", type=6, model=5},
            new { maker="Volvo", type=2, model=0},
            new { maker="Volvo", type=1, model=2},
            new { maker="GM", type=1, model=0},
            new { maker="GM", type=0, model=20},
            new { maker="GM", type=9, model=5},
            new { maker="GM", type=9, model=50},
            new { maker="GM", type=9, model=25},
        };
    var results = list
        .GroupBy(x => x.maker, (key, g) => g.OrderByDescending(e => e.type).First())
        .ToList();

Returns

{ maker = Volvo, type = 8, model = 10 }

{ maker = GM, type = 9, model = 5 }

Which is closed to what I want and if I keep extending it to

       var results = list
        .GroupBy(x => x.maker, (key, g) => g.OrderByDescending(e => e.type).GroupBy(z => z.type, (key1, y) => y.OrderByDescending(u => u.model).First()))
        .ToList();

Returns nothing

vs. Expected result

{ maker = Volvo, type = 8, model = 100 }

{ maker = GM, type = 9, model = 50 }

So how do I fix this?

CodePudding user response:

You just need a ThenByDescending instead of another GroupBy:

var results = list
    .GroupBy(x => x.maker, 
            (key, g) => g.OrderByDescending(e => e.type)
                         .ThenByDescending(e => e.model)
                         .First())
    .ToList();
  • Related