Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore 'null' in order by clause

Tags:

linq

How i can ignore Null in name property when orderby

student.Students= student.student.OrderBy(s=> s.Name ?? null).ToList();

The above code always return list of students having Name = null as 1st element in the list and student with name 'system' in the end.

What i want to ignore/exclude null in orderby. the null should always come to end of the the list

like image 497
simbada Avatar asked Oct 17 '25 10:10

simbada


1 Answers

You can make a conditional OrderBy:

student.Students= student.student
    .OrderBy(s=> s.Name == null ? 1 : 0)
    .ThenBy(s => s.Name)
    .ToList();

This splits first into two groups, the items with s.Name != null and those with s.Name == null. The second sort-condition is the Name itself.

like image 192
Tim Schmelter Avatar answered Oct 19 '25 14:10

Tim Schmelter