gpt4 book ai didi

c# - Linq-按自定义顺序发布

转载 作者:行者123 更新时间:2023-11-30 22:13:21 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com