2

I have a list of objects which are grouped by a particular property. I need to sort this list based on other properties, but it always needs to retain the grouping. So for example, if the list is something like:

{ id=1, partNumber = 100 }
{ id=2, partNumber = 500 }
{ id=2, partNumber = 300 }
{ id=2, partNumber = 600 }
{ id=3, partNumber = 550 }
{ id=3, partNumber = 990 }
{ id=4, partNumber = 200 }
{ id=5, partNumber = 300 }

then the result after sorting by part number ascending would be:

{ id=1, partNumber = 100 }
{ id=4, partNumber = 200 }
{ id=5, partNumber = 300 }
{ id=2, partNumber = 400 }
{ id=2, partNumber = 500 }
{ id=2, partNumber = 600 }
{ id=3, partNumber = 550 }
{ id=3, partNumber = 990 }

It sorts by the minimum PartNumber in each group (or maximum if the sort is descending), but must remain grouped by ID. I have tried various combinations of .OrderBy() and .GroupBy(), but I can't seem to get what I need.

drowned
  • 530
  • 1
  • 12
  • 31
  • At what point are you grouping the results? Are you grouping at the database level, like through a stored procedure, or is the grouping also done through LINQ? – James Johnson Aug 29 '11 at 17:20

2 Answers2

5
var orderedList = 
    list.GroupBy(i => i.id)
        .OrderBy(g => g.Min(i => i.partNumber))
        // and if you want to flatten the groupings back out
        .SelectMany(g => g);
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

Your before/after test sample doesn't match up, but this should solve your problem.

 var query = from a in list
             orderby a.partNumber
             group a by a.id into ag
             orderby ag.Min(x => x.partNumber)
             from a in ag
             select a;
Aducci
  • 26,101
  • 8
  • 63
  • 67
  • My before test sample was an arbitrary list. I'm pretty sure the after sample matches up, in terms of being grouped by ID, ordered by part number. What do you mean? – drowned Aug 29 '11 at 18:08
  • @drowned - In your first set you have **id=3, partNumber = 900**, that is not in your ordered set, but you have **id=3, partNumber = 550** – Aducci Aug 29 '11 at 18:16
  • ah, a typo, ok. I thought you were saying that the sort was wrong. Got it, thanks. – drowned Aug 29 '11 at 20:21