Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 257
Jeff Avatar asked May 05 '10 06:05

Jeff


People also ask

Can you use LINQ on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

How do I get data in descending order in LINQ?

If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

How do you order alphabetically in LINQ?

SelectedValue) . OrderBy(s=> s.Name). ToList(); The order by does nothing, just executes the query, the ToList will do the sort for the original query.

How do I use ascending order in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.


1 Answers

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.

like image 145
leppie Avatar answered Oct 06 '22 14:10

leppie