Home > database >  Group by and then order within groups in C#
Group by and then order within groups in C#

Time:11-12

Let's assume a list of objects with two properties - int Val1 and double Val2. I want to group it by Val1, and then order within groups by Val2.

Example list:

Val1 Val2
1    2.4
2    1.3
1    1.9
2    5.1

Properly grouped and ordered list would look like:

Val1 Val2
1    1.9
1    2.4
2    1.3
2    5.1

The first thing that comes to my mind is using LINQ.

list = list.GroupBy(x => x.Val1).SelectMany(x => x).OrderBy(x => x.Val2).ToList();

But results are not correct - OrderBy entirely overrides GroupBy.

Approach with different order of methods almost works:

list = list.OrderBy(x => x.Val2).GroupBy(x => x.Val1).SelectMany(x => x).ToList();

But Val1 are reversed - go from higher to lower value, while Val2 is ordered correctly. Can't just reverse list, since it would reverse Val2.

CodePudding user response:

I want to group it by Val1, and then order within groups by Val2.

I think you want something else: you want to order the list by Val1 and then by Val2:

list = list
    .OrderBy(x => x.Val1)
    .ThenBy(x => x.Val2)
    .ToList(); 

It doesn't make sense to create groups and then flatten them if all you want is ordering.

  • Related