var CustomStatus = new[] { "PAG", "ASG", "WIP", "COMP", "SEN" };
List<CDSHelper> HelperList = new List<CDSHelper>();
// Getting the values from API to fill the object and
// finally doing the custom order by
var result = HelperList.OrderBy(a => Array.IndexOf(CustomStatus, a.status));
我正在使用自定义顺序对 HelperList 对象进行排序。我总共有大约 18 个状态。在 18 个状态中,我想根据 CustomStatus 对列表进行排序,其余订单应位于 CustomStatus 状态之后的列表中。使用上面的代码我可以在 HelperList 的末尾获取 CustomStatus 。如何实现这一目标?
最佳答案
可能最简单的方法是使用 OrderBy
然后使用 ThenBy
但是您需要更改 -1
IndexOf
如果该项目不存在,则会返回更高的值,因此不在列表中的项目将成为最后一个。
var result = HelperList.OrderBy(a => {
var x = Array.IndexOf(CustomStatus, a.status);
if(x < 0)
x = int.MaxValue;
return x;
}).ThenBy(a => a.status); //Sort alphabetically for the ties at the end.
另一种方法是反转 CustomStatus
的顺序,然后使用 OrderByDecending
var CustomStatus = new[] { "SEN", "COMP", "WIP", "ASG","PAG" };
List<CDSHelper> HelperList = new List<CDSHelper>();
// Getting the values from API to fill the object and
// finally doing the custom order by
var result = HelperList.OrderByDecending(a => Array.IndexOf(CustomStatus, a.status))
.ThenBy(a.status);
关于c# - Linq-按自定义顺序发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19194388/