1

Is is possible to use LINQ to sort groups using a different orderby clause? For example in one group I want to sort the results in ascending order and then in a different group sort in descending order by using a property that would determine the sort direction.

I can do this by looping through the groups and apply sorting on the group, however my question is whether this can be done as part of the original LINQ query? Would there be any negative performance implications of doing this?

Intrepid
  • 2,781
  • 2
  • 29
  • 54
  • possible duplicate of [How to use Dynamic LINQ in MVC4?](http://stackoverflow.com/questions/22005488/how-to-use-dynamic-linq-in-mvc4) – alexmac Feb 25 '14 at 09:54
  • Where would "*a property that would determine the sort direction*" be pulled from? That's critical as to how this will work. – James Feb 25 '14 at 09:56

1 Answers1

1

If you have some sort of property in the group that you can use to sort, then yes it can do this in one go. For example, this code will group by an int property and determine the sort type based on whether the value is positive or negative

var query = from i in someTable
            group i by i.SomeIntProperty into g
            let sortAsc = g.Key % 2 == 0 
            select new 
            {
                Key = g.Key,
                Results = sortAsc ? g.OrderBy(x => x.SomeProperty) : 
                    g.OrderByDescending(x => x.SomeProperty)
            }
James
  • 80,725
  • 18
  • 167
  • 237
  • I was about to respond to your comment that the property is held in the class containing the data to be sorted so your solution looks like a good one to me. I will give that a try now and see if it works for me. Cheers! – Intrepid Feb 25 '14 at 10:11