Intrepid
Intrepid

Reputation: 2831

Dynamic order by clause in a single LINQ query

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?

Upvotes: 1

Views: 340

Answers (1)

James
James

Reputation: 82096

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)
            }

Upvotes: 1

Related Questions