How to OrderBy on a generic IEnumerable (IEnumerable<T>) using LINQ in C#?

Jeff picture Jeff · May 5, 2010 · Viewed 14.4k times · Source

In my generic repository I have below method:

public virtual IEnumerable<T> GetAll<T>() where T : class
{
    using (var ctx = new DataContext())
    {
        var table = ctx.GetTable<T>().ToList();
        return table;
    }
}

T is a Linq to Sql class and I want to be able to OrderBy on a particular property (i.e. int SortOrder). Say if T has property name "SortOrder" then do OrderBy on this property. But I am not sure how I can achieve this. So I need some helps. Thank you! I feel like dynamic languages really shines in doing this kind of jobs!

Quote from ScottGu:

While writing type-safe queries is great for most scenarios, there are cases where you want the flexibility to dynamically construct queries on the fly

And this is exactly the problem I am facing and I am wondering if this linq dynamic helper can be made into official .NET library.

Answer

leppie picture leppie · May 5, 2010
public IEnumerable<T> GetAll<T,K>(Expression<Func<T,K>> sortExpr)
{
  using (var ctx = new DataContext())
  {
    ctx.ObjectTrackingEnabled = false;
    var table = ctx.GetTable<T>().OrderBy(sortExpr).ToList();
    return table;
  }
}

Usage:

var t = GetAll<Foo, int>(x => x.Bar);

Unfortunately, you have to supply the type of the key. Unless you start messing with the expressions.