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.

1
  • 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? Commented Aug 29, 2011 at 17:20

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

and probably a SelectMany to ungroup afterwards
SelectMany seems to be what I was missing. Thanks a lot.
Add a .OrderBy(i => i.partNumber) first and that will give the desired output
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;

3 Comments

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 - In your first set you have id=3, partNumber = 900, that is not in your ordered set, but you have id=3, partNumber = 550
ah, a typo, ok. I thought you were saying that the sort was wrong. Got it, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.