Linq-按自定义顺序发布

时间:2013-10-05 05:35:15

标签: c# linq

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。如何实现这个目标?

2 个答案:

答案 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中包含的所有值,然后是其余值。然后按状态按字母顺序排序每个组。