Custom sorting a data set has been a problem since the beginning of data sets. With the Generic List and Linq custom sorting is now easier than ever. Custom sorting by more than one field is easier than ever.
This example uses the Orderby and ThenBy functions of the Generic List.
These are the assumptions for this code
- You’ve already built and filled the generic list with data.
- You’ve included “Imports System.Linq” in your class
Once you have your list you can send it through the “SortMyList” function. The SortMyList function receives one parameter; the generic list you’ve created. In this case we’re calling it “myList” – change the name to whatever you want to call your list.
The list type is the class name for your list that contains all the properties and functions for your list. This one is called GenericListInfo, but you can change that to whatever your class name is called.
The function returns a generic list of the same type.
Private Function SortMyList(MyList As List(Of GenericListInfo)) As List(Of GenericListInfo) Try Dim sortedList As New List(Of GenericListInfo) sortedList = myList.OrderBy(Function(mts) mts.FirstField).ThenBy(Function(mts) mts.SecondField).ToList Return sortedList Catch ex As Exception 'code for throwing error goes here Return Nothing End Try End Function
What the code is doing
First the list is sent to the function.
“sortedList” is a new empty list of the same type.
The first OrderBy function of the list is the main sort. After the OrderBy, add as many sorts as needed using the ThenBy function. The ThenBy’s are sorted in order after the OrderBy, so list them in the order you want them to be sorted.
The final method “ToList” is necessary to cast an enumerable list to a generic list. If you’re getting the error
Unable to cast object of type ‘System.Linq.OrderedEnumerable`2[GenericListInfo,System.String]’ to type ‘System.Collections.Generic.List`1[GenericListInfo]’.
The problem is likely that you need to add “ToList” to the end of your sorting string.
Finally, return the new sortedList.
Any questions, or tips, for sorting a list? Leave them in the comments.
For a version of this in C# visit Arnold Matusz’s blog.