About the author

Miron Abramson
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments



The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2018

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

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<T> Sort<T>(this IEnumerable<T> source, string sortExpression)
    string[] sortParts = sortExpression.Split(' ');
    var param = Expression.Parameter(typeof(T), string.Empty);
        var property = Expression.Property(param, sortParts[0]);
        var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);

        if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
            return source.AsQueryable<T>().OrderByDescending<T, object>(sortLambda);
        return source.AsQueryable<T>().OrderBy<T, object>(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<User> collection: users. You can sort it however you want:

IEnumerable<User> sortedUsersIEnumerable = users.Sort<User>("ID desc"); 


List<User> sortedUsersList = users.Sort<User>("Name").ToList();

I really think this extension should be 'built-in' part of the 'Linq'. 

Extensions.cs (1.08 kb)

Currently rated 4.5 by 10 people

  • Currently 4.500001/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | C# | Server side
Posted by Miron on Wednesday, May 07, 2008 1:59 PM
Permalink | Comments (7) | Post RSSRSS comment feed

Related posts


Bart Czernicki us

Thursday, May 08, 2008 10:33 AM

Bart Czernicki

Very nice. I wrote something like this for a tool I was writing for dynamically interactive grids (bind to any data source and you get sorting/filtering etc) all out of the box.

dave us

Tuesday, July 29, 2008 1:24 AM


very cool! This and the PredicateBuilder (www.albahari.com/nutshell/predicatebuilder.html ) make LINQ virtually unstoppable for databinding asp.net grids and filtering.

ps Something is wrong with your url parsing script it's messing the pasted link all up if I put my own 'http' in front of it.

Minal nz

Monday, February 23, 2009 3:35 PM


Very neat.
You just saved me re-inventing your wheel Smile

Thanks a million.

Jason us

Friday, March 27, 2009 12:47 PM


thanks a lot! this helped me a ton

sachin singh in

Monday, October 05, 2009 10:01 PM

sachin singh

Thanx a lot !!!! you saved my lot of time in time critical situation.

Thanx Smile

Nazir gb

Monday, November 02, 2009 11:04 PM


Very nice code..
I am very new to 3.5 and going through Linq stuff and trying to work out this example.
problem is when you write users.sort(...) is sort method is part of users collection i mean List<User> or somthing else...
I have tried to use this exapmle in window application, i have copied the above code and pasted in form1.class and then tried to use
user.sort method but geting compiled time error "The non-generic method ...... can not be used with type arguments".
So question is how can this genric sort method recognizsed by compiler for List<User> class?

Please advise.

Prompt action will be appriciated.

Nazir gb

Monday, November 02, 2009 11:09 PM


Well It's working now!!!

Well i have worked it out puting code in a static class (forgot in first attempt)

Does it work with nested object i mean if we have an Address object inside the user class???