Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq ThenBy Possibly Null

Tags:

c#

linq

I'm trying to sort a view model binding on multiple properties. The problem is that the second property might be null, and I get a null reference exception.

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet.Name);

What if Pet is null? How do I still do a ThenBy sort by Pet.Name?

like image 216
Bob Horn Avatar asked Dec 06 '22 13:12

Bob Horn


1 Answers

This should return null Pets before non-null Pets.

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet != null ? x.Pet.Name : "");
like image 105
Kendall Frey Avatar answered Dec 10 '22 03:12

Kendall Frey