2016-03-07 67 views
2

我怎麼能忽略name屬性空當排序依據如何才能忽略「空」的條款

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

上面的代碼總是返回列表list of students having Name = null as 1st elementstudent with name 'system' in the end.

我想ignore/exclude null in orderby什麼。 n個ull should always come to end of the the list

回答

3

您可以有條件OrderBy

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

這首先分成兩組,s.Name != null和那些s.Name == null的項目。第二種排序條件是Name本身。

+0

清潔,簡單,流暢... +1 –

+0

@Tim Schmelter謝謝,1:0代表第三行代碼的含義是什麼? – simbada

+0

@simbada:它只是排序值,如果名稱爲空,則採用'1',如果不爲空'0'則採用。由於0小於1,所以非空值先來。你也可以編寫:'.OrderBy(s => s.Name == null)'。這將工作,因爲結果是一個'布爾',其中'真'比'假'更「大」。 –