Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerable OrderBy - are null values always treated high or low and can this be considered stable behaviour?

Tags:

c#

null

sorting

I am sorting some IEnumerable of objects:

var sortedObjects = objects.OrderBy(obj => obj.Member)

Where Member is of an IComparable type. This sort seems to put objects with obj.Member == null at the top. This is roughly the behaviour that I want, but can I consider this to be stable with respect to future .NET frameworks? Is there a way I can make this 'nulls are low' behaviour more explicit?

like image 846
silasdavis Avatar asked Jul 21 '11 17:07

silasdavis


People also ask

Is LINQ OrderBy stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.

How are NULL values handled when data is sorted?

If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.

How do you handle NULL values in LINQ query?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=

Which is the right answer to the following order by name asc displays NULLs last?

The answer is - SQL Server treats NULL values as the lowest values. For example when sorted in ascending order, NULLs come first.


3 Answers

To make the behavior more explicit:

var sorted = objects.OrderBy(o => o.Member == null).ThenBy(o => o.Member);
like image 127
Cheng Chen Avatar answered Nov 13 '22 18:11

Cheng Chen


From MSDN for IComparable:

By definition, any object compares greater than (or follows) null, and two null references compare equal to each other.

So a null object is considered less than a non-null object. If sorting ascending, you will get nulls first.

like image 41
Jason Down Avatar answered Nov 13 '22 18:11

Jason Down


One option is to use the overload of OrderBy that takes an IComparer<T> and implement it yourself to codify this expectation:

http://msdn.microsoft.com/en-us/library/bb549422.aspx

like image 22
Pete Avatar answered Nov 13 '22 17:11

Pete