Google+

Friday, January 14, 2011

Sorting a collection using Linq and 'SortExpression' string

Already happened to you that you had a collection of object from type 'X' with some properties, and you had to sort it one time by property 'ID', and another time by property 'Name' ? You wished that you can sort it by just using a 'Sort Expression' ? If still not, I'm sure this moment will arrive sooner or later. Let me save you some time and an headache.
This is how it can be done: 

 public static IEnumerable Sort(this IEnumerable source, string sortExpression)
{
    string[] sortParts = sortExpression.Split(' ');
    var param = Expression.Parameter(typeof(T), string.Empty);
    try
    {
        var property = Expression.Property(param, sortParts[0]);
        var sortLambda = Expression.Lambdaobject>>(Expression.Convert(property, typeof(object)), param);

        if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
        {
            return source.AsQueryable().OrderByDescendingobject>(sortLambda);
        }
        return source.AsQueryable().OrderByobject>(sortLambda);
    }
    catch (ArgumentException)
    {
        return source;
    }
}

Just drop it in a static class, and you will be able to sort any collection that implement the interface IEnumerable.
Lets say you have a class 'User':
public class User
{
    public int ID { get; set; }
    public string Name { get; set; }
}
and a List collection: users. You can sort it however you want:

IEnumerable sortedUsersIEnumerable = users.Sort("ID desc"); 
Or
List sortedUsersList = users.Sort("Name").ToList();
I really think this extension should be 'built-in' part of the 'Linq'. 


Note:-Please comment and reply me.

0 comments:

Post a Comment