Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property

Once stuck on a requirement where I needed to write a code which is flexible and generic enough to sort any type of collection and also the property based on which it has to be sorted will be dynamic. After trying many options I discovered myself how easy it is to hit this requirement using Lamda Expression.

 

 

Below code will do this for you.

public class Utility
{
///
/// Gets the sorted list.
///

///The source.
///The sort column.
///The sort direction.
/// private List GetSortedList(List source, string sortColumn, SortDirection sortDirection)
{
// Prepare the dynamic sort expression
var paramExp = Expression.Parameter(typeof(T), typeof(T).ToString());
Expression propConvExp =
Expression.Convert(Expression.Property(paramExp, sortColumn), typeof(object));
var sortExp = Expression.Lambda>(propConvExp, paramExp);

if (sortDirection == SortDirection.Ascending)
{
return source.AsQueryable().OrderBy(sortExp).ToList();
}
else
{
return source.AsQueryable().OrderByDescending(sortExp).ToList();
}
}
}

We will call this method as below

List sortedEmployees
= new Utility().GetSortedList(employeeList, "City", SortDirection.Ascending);

First we create the parameter expression for the generic type and on the further two statements we are promting the expression to convert the dynamic property based on which we need to sort to a understandable format of lambda. Then we go ahead and use the sort of generic list.

You can find the complete post over here as well

Jebarson

Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net, ASP.net, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at http://www.jebarson.info/ . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them http://bit.ly/houBNx . He is a contributor of this site and shared many tips and tricks.