Sorting objects has been a programming problem that has gone from a science to a mere few lines of code. Though it does not take nearly
the amount of consideration as it did before my time in the industry, it's still just as relevant. This article takes a look at sorting using
Lambda Expressions and Generics. In my opinion, the best technique for sorting objects that I have seen so far. This class has found a definite
home in my Utils assembly, and so I share it with you.
As programmers, it is always our duty, and pleasure, to find better ways to the same thing. That is how I stumbled on this sorting technique.
I was working on a project that had several grids that required paging and sorting, and like many projects, we were using an object model.
I was thinking that I wanted a generic sorting class that did all the work in one place, and this article shares the results.
Using the code
These samples have been dumped down a little from my actual implementation to improve readability for the purposes of this article.
After reviewing this code though, I am confident that you will be able to think of several slick uses for this technique like I have.
Usage of the sorting class
GenericSorter<surveystateformatdata> gs = new GenericSorter<surveystateformatdata >();
SurveyStateFormatItems = gs.Sort(SurveyStateFormatItems.AsQueryable,
Dim gs As New GenericSorter(Of SurveyStateFormatData)
SurveyStateFormatItems = gs.Sort(SurveyStateFormatItems.AsQueryable, _
Here is the sorting class:
public class GenericSorter<T>
public IEnumerable<T> Sort(IEnumerable<T> source, string sortBy, string sortDirection)
var param = Expression.Parameter(typeof(T), "item");
var sortExpression = Expression.Lambda<Func<T, object>>
(Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param);
return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);
Public Class GenericSorter(Of T)
Public Function Sort(ByVal source As IEnumerable(Of T), _
ByVal sortBy As String, _
ByVal sortDirection As String) As IEnumerable(Of T)
Dim param = Expression.Parameter(GetType(T), "item")
Dim sortExpression = Expression.Lambda(Of Func(Of T, Object))_
(Expression.Convert(Expression.[Property](param, sortBy), _
Select Case sortDirection.ToLower
- Article added: (06/22/2009).