tags:

views:

525

answers:

3

In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).

Something like this (not valid code):

bool flag;

(from w in widgets
 where w.Name.Contains("xyz")
 orderby w.Id (flag ? ascending : descending)
 select w)
+3  A: 

If you build the expression incrementally you can do this. Generally easier using expressions rather than comprehension expressions:

var x = widgets.Where(w => w.Name.Conatins("xyz"));
if (flag) {
  x = x.OrderBy(w => w.property);
} else {
  x = x.OrderByDescending(w => w.property);
}

(Assuming the Widget's property is basis of sort since you don't list one.)

Richard
+3  A: 

You can define a base query without the ordering, then order according to the flag:

var query=(from w in widgets
  where w.Name.Contains("xyz")
  select w);

var result = flag ?
  query.OrderBy(w =>w) :
  query.OrderByDescending(w = w);
Konamiman
+3  A: 

You could try something like the following:

var q = from i in list
         where i.Name = "name"
         select i;
if(foo)
     q = q.OrderBy(o=>o.Name);
else
     q = q.OrderByDescending(o=>o.Name);
cloggins