Thursday, February 17, 2011

LINQ : Notes about sorting

The Ascending Keyword:
The default order for the orderby keyword is ascending. So in actuality specifing ascending in a LINQ query is only there for explicit mentioning for the ease of the programmer and is ignored by the compiler.

In fact orderby translates into one of four possible extension methods by the compiler:


A bit more:
http://dotnetperls.com/ascending

The return type is IOrderedEnumerable
IOrderedEnumerable inherits from IEnumerable and the reason it exits is because of ThenBy and ThenByDescending . These extension method only function on IOrderedEnumberable.

These are called when you politely write such linq queries:

var expr = from c in customers 
                      orderby c.Name descending, c.City
                                   select new { c.Name, c.City };



the c.City sorting is actually added using ThenBy.

Also bet you didn't know Reverse
Although it has no corresponding LINQ query syntax and you need to use the Extension method. It simply reorders the first item to be last etc.

What is the algorithm used by LINQ for sorting?
LINQ to objects uses quicksort. You can verify this by opening up System.Linq.EnumerableSorter in reflector.
For any other implementation of LINQ it is up to the implementation (ofcourse) e.g LINQ2SQL it will get traslated to SQL order by and it will be up to SQL Server to carry out the sorting and pick a sorting algorithm.