How to Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property ? - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Saturday, May 28, 2011

How to Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property ?

eneric enough to sort any type of collection and also the property based on which it has to be sorted will be dynamic.This is very much easy to hit this requirement using Lamda Expression.

Below code will do this for you.

[sourcecode language="csharp"]
public class Utility
{
/// <Summary>
/// Gets the sorted list.
/// </Summary>
/// <param name="source" />The source.
/// <param name="sortColumn" />The sort column.
/// <param name="sortDirection" />The sort direction.
/// <The sorted list. />
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();
}
}
}
[/sourcecode]
We will call this method as below
[sourcecode language="csharp"]
List<Employee> sortedEmployees
= new Utility<Employee>().GetSortedList(employeeList, "City", SortDirection.Ascending);
[/sourcecode]
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.

Original Source

No comments:

Post a Comment