John Stab John Stab -4 years ago 124
C# Question

c# Sort list item group without sorting the entire list

I have to sort a list of items like the following

Order Category Data Type
1 Unknown NULL NULL
5 Item 26:59.2 Suspense
5 Item 35:10.1 General
5 Item 35:22.6 General
5 Item 45:24.0 General
5 Item 02:16.6 General
5 Item 37:10.4 Bank
6 Hidden NULL NULL


And i want to sort by Data the ones with Order = 5 and Type = General but not changing the position for the Bank or Suspense .
I will always have the Order = 5 grouped, but i might have different Types before and after General Type.

Expected result:

Order Category Data Type
1 Unknown NULL NULL
5 Item 26:59.2 Suspense
5 Item 02:16.6 General
5 Item 35:10.1 General
5 Item 35:22.6 General
5 Item 45:24.0 General
5 Item 37:10.4 Bank
6 Hidden NULL NULL


Can someone help me?
Thanks.

Answer Source

The "obvious" solution is to split the list into 3 sections and sort the middle bit:

//First part
var start = things.TakeWhile(t => t.Order != 5 || t.Type != "General");

//Middle part
var middle = things
    .SkipWhile(t => t.Order != 5 || t.Type != "General")
    .TakeWhile(t => t.Order == 5 && t.Type == "General")
    .OrderBy(t => t.Data);

//Last part:
var end = things
    .SkipWhile(t => t.Order != 5 || t.Type != "General")
    .SkipWhile(t => t.Order == 5 && t.Type == "General");

And finally merge them into a single list:

var merged = start.Concat(middle).Concat(end);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download