sf. sf. - 1 month ago 15x
C# Question

LINQ order by null column where order is ascending and nulls should be last

I'm trying to sort a list of products by their price.

The result set needs to list products by price from low to high by the column

. However, this column is nullable.

I can sort the list in descending order like so:

var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;

// returns: 102, 101, 100, null, null

However I can't figure out how to sort this in ascending order.

// i'd like: 100, 101, 102, null, null


Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

Otherwise each orderby is a separate operation on the collection re-ordering it each time.

This should order the ones with a with a value first, "then" the order of the value.