针对字符串值的解决方案真的很奇怪:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
唯一有效的原因是第一个表达式
OrderBy()
对
bool
值进行排序:
true
/
false
。先排列出
false
的结果,然后是
true
的结果(可空值),
ThenBy()
对非空值按字母顺序进行排序。
e.g.: [null, "coconut", null, "apple", "strawberry"]
First sort: ["coconut", "apple", "strawberry", null, null]
Second sort: ["apple", "coconut", "strawberry", null, null]
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);