Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort blank entries to bottom of LINQ query

I am trying to sort a LINQ to SQL query based on two fields. The first field is occasionally null which automatically sorts to the top of an ascending query. Is there any way to make the null entries sort to the bottom?

Here is an example:

From x in SampleDataContext.Event _
Order By x.Date, x.Sequence_Number _
Select x.Date, x.Sequence_Number

Would return:

  • NULL, 1
  • NULL, 4
  • 12/2/09, 5
  • 12/3/09, 2
  • 12/3/09, 3

Desired order:

  • 12/2/09, 5
  • 12/3/09, 2
  • 12/3/09, 3
  • NULL, 1
  • NULL, 4
like image 320
sglantz Avatar asked Dec 02 '09 16:12

sglantz


People also ask

How do I sort in LINQ descending order?

If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

What is OrderBy in LINQ?

Sorts the elements of a sequence in ascending order according to a key. OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) Sorts the elements of a sequence in ascending order by using a specified comparer.

How would you sort the list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

Is LINQ case sensitive?

LINQ StartsWith , EndsWith , and Contains are case sensitive and return false if two same string s are of different cases, e.g., " STRING " and " string ".


1 Answers

If they're strings:

Order By (string.IsNullOrEmpty(x.Date) ? "zzzzzz" : x.Date)

If they're nullable datetimes:

Order By (x.Date ?? DateTime.MaxValue)
like image 51
David Hedlund Avatar answered Sep 23 '22 09:09

David Hedlund