sf. sf. - 1 year ago 104
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download