How to use Orderby to create dynamic linq queries?

I have a linq request that looks like this

string sortby="Date"; //it can be name or something else as well var query=(from t in Uow.Transactions.GetAllWithReferences() orderby t.Date descending select t); 

But I want to order differently based on the value of the sortby variable. How can I do this with Linq?

+4
source share
4 answers

For sample class:

 private class Tst { public int field1 { get; set; } public string field2 { get; set; } public string field3 { get; set; } } 

You can do it as follows:

 var index = 1; var sortedList = (from l in list orderby index == 1 ? l.field1.ToString() : index == 2 ? l.field2 : l.field3 select l); 

But since the fields have different types, you need to make some type, as you see l.field1.ToString()

How do you do this using lambda:

 var sortedList = list.OrderBy(l => index == 1 ? l.field1.ToString() : index == 2 ? l.field2 : l.field3) .Select(l => l).ToList(); 
+1
source

Using reflection:

 string sortby="Date" //it can be name or something else as well var query=(from t in Uow.Transactions.GetAllWithReferences() orderby t.GetType().GetProperty(sortby).GetValue(t, null) descending select t); 
+1
source

If you use the OrderBy () LINQ extension method, you can pass a predicate, which can be something like (untested):

 Predicate orderByClause; if ( blah == "date" ) orderByClause = { order => order.Date }; if ( blah == "something else" ) orderByClause = { order => order.SomethingElse }; var oSortedList = oResultList.OrderBy( orderByClause ); 

I am sure the syntax is if it is turned off, but I did something similar before ...

Hope this helps!

+1
source

You can use the library for this, here is one of my favorites: http://dynamite.codeplex.com/

+1
source

Source: https://habr.com/ru/post/1469234/


All Articles