C# object sorting by group, using linq
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 r开发者_StackOverflow社区etain 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.
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);
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;
精彩评论