Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting with Nulls Last

Tags:

c#

.net

linq

I have the following:

public IEnumerable<Customer> SortByRegion(IEnumerable<Customer> customerList)
{
    return customerList.OrderBy(x => x.Region).ThenBy(x => x.ContactName);
}

It needs to Orderby Region, then by ContactName. But have the Null Regions at the bottom. I have tried the following:

customerList.OrderBy(x => x.Region != null).ThenBy(x => x.ContactName);

But id did not work. Been googling for a while. Cant seem to find it.

like image 324
Mathieu Leclerc Avatar asked Nov 26 '25 05:11

Mathieu Leclerc


1 Answers

You can do something like this:

OrderBy(x => x.Region != null ? 1 : 0)
like image 160
Salah Akbari Avatar answered Nov 27 '25 17:11

Salah Akbari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!