说我有ListA={null,3,2,null}.
ListA.OrderBy(x=>x.ID) //would return me null,null,2,3
Run Code Online (Sandbox Code Playgroud)
如果我的目标是获得2,3,null,null,目前我只能想到提取出空项目,并手动泵入后面.
有一个干净的方法会让我回来2,3,null,null吗?
你可以使用OrderByDescending + ThenBy(假设它是a List<int?>):
var orderedList = ListA
.OrderByDescending(x => x.HasValue)
.ThenBy(x => x);
Run Code Online (Sandbox Code Playgroud)
x.HasValue返回true或高于的false地方.这就是我使用的原因.truefalseOrderByDescending
如果要排序的原始列表我会用List.Sort一个自定义Compaison<T>的是把null作为最高的价值:
ListA.Sort((a1, a2) => (a1 ?? int.MaxValue).CompareTo(a2 ?? int.MaxValue));
Run Code Online (Sandbox Code Playgroud)
这样更有效,因为它不需要创建新列表.
| 归档时间: |
|
| 查看次数: |
1293 次 |
| 最近记录: |