Search code examples
c#sortingsortedlistcolumnsorting

Sort columns using SortedList


I have a table data with many columns, I need to sort it by multiple times. e.g. the columns contain Row#, Name, allowance, times...

1, Peter,   2500,  2
2, Steve,    500,  1
3, Peter,   2500,  1
4, Peter,   2600,  2
5, Peter,   2800,  2

1st Sort by Name ascending, the result is:

1, Peter,   2500,  2
3, Peter,   2500,  1
4, Peter,   2600,  2
5, Peter,   2800,  2
2, Steve,    500,  1

2nd Sort by allowance descending, the result is:

5, Peter,   2800,  2
4, Peter,   2600,  2
1, Peter,   2500,  2
3, Peter,   2500,  1
2, Steve,    500,  1

3rd Sort by times ascending, the result is:

5, Peter,   2800,  2
4, Peter,   2600,  2
3, Peter,   2500,  1
1, Peter,   2500,  2
2, Steve,    500,  1

Due to some reason, We used SortedList to do the first sort using IComparer to add item to SortedList to allow duplicated keys. After 1st sort by Name ascending, sortedList is:

["Peter"] | 1
["Peter"] | 3
["Peter"] | 4
["Peter"] | 5
["Steve"] | 2

The 1st sort is done, but how to do 2nd and 3rd... sort based on this 'Master' sortedList? My idea is that 2nd sort is happened within neighbors w/ the same Key e.g. "Peter". means only need to re-sort Row# 1,3,4,5 for 2nd Sort. But I can't think the best way.


Solution

  • You can use LinQ on your Sorted list:

    var Customsortedlist =  SortedList<T>.OrderBy(e => e.Name)
                                         .ThenByDescending(e => e.Allowance)
                                         .ThenBy(e => e.times );
    

    Then you can convert it like this :

    dataTable = Customsortedlist.AsDataView().ToTable();