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.
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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With