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 status后的列表中。上面的代码我能够在HelperList的末尾获得CustomStatus。如何实现这个目标?
答案 0 :(得分:3)
可能最简单的方法是使用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);
答案 1 :(得分:0)
为CustomStatus
创建HashSet
。您无需知道CustomStatus
中状态的索引,只需要知道它是否在列表中。 HashSet
中的查找是O(1)操作。在数组中,它是O(n):
var CustomStatus = new HashSet<string> { "PAG", "ASG", "WIP", "COMP", "SEN" };
var result = HelperList.OrderBy(a => !CustomStatus.Contains(a.status))
.ThenBy(a => a.status).ToList();
OrderBy
按照!CustomStatus.Contains(a.status)
返回的布尔值对列表进行排序。首先是HashSet
中包含的所有值,然后是其余值。然后按状态按字母顺序排序每个组。