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:
Desired 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.
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.
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.
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 ".
If they're strings:
Order By (string.IsNullOrEmpty(x.Date) ? "zzzzzz" : x.Date)
If they're nullable datetimes:
Order By (x.Date ?? DateTime.MaxValue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With