4

I have linq query which is as follows

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 orderby differently based on sortby variable value. How can i do that using Linq?

Satinder singh
  • 10,100
  • 16
  • 60
  • 102
Imran Jawaid
  • 471
  • 1
  • 10
  • 27
  • 4
    consider this thread http://stackoverflow.com/questions/41244/dynamic-linq-orderby/233505#233505 – Ilya Ivanov Mar 14 '13 at 12:52
  • here is a good link that would probably give you a better understanding on how to use the `from` clause. since you basically stated that it can be anything perhaps you need to look at the section that talks about the `Where` clause http://www.programmersheaven.com/2/CSharp3-4 – MethodMan Mar 14 '13 at 12:54

4 Answers4

1

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);
Jacob VanScoy
  • 1,168
  • 6
  • 14
  • I tried this but after doing this when u try to do query.tolist() it crash. Any idea y ? – Imran Jawaid Mar 14 '13 at 13:31
  • I tested this querying a simple IEnumerable. If you are using the Entity Framework, you can't use reflection like this inside those queries. See this post here: http://stackoverflow.com/questions/4546463/help-with-linq-and-generics-using-getvalue-inside-a-query – Jacob VanScoy Mar 14 '13 at 14:51
1

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 this way:

var index = 1;

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

But as fields have different types you have to do some type cast as you see l.field1.ToString()

Way you do it using lambda is:

var sortedList =
    list.OrderBy(l => 
            index == 1 ? l.field1.ToString() 
            : index == 2 ? l.field2 
            : l.field3)
        .Select(l => l).ToList();
Sergio
  • 6,900
  • 5
  • 31
  • 55
1

If you use the OrderBy() LINQ extension method, you can pass in a predicate which could 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'm sure the syntax if way off, but I have done something like this before...

Hope this helps!

1

You can use a library for that, here is one of my favorite : http://dynamite.codeplex.com/

andri
  • 1,021
  • 1
  • 9
  • 16