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

标签 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 状态之后的列表中。使用上面的代码我可以在 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/

相关文章:

c# - 根据每个模型请求往返数据库?

c# - XXTEA的返回值

c# - 如何在编辑模式 ASP .Net 中将日期选择器放入 Gridview

c# - 如何在列表中使用 "Contain"?

c# - Linq lambda 表达式至少得到一个重复项和非重复项

c# - 将 SQL Rank() 转换为 LINQ 或替代方法

c# - Entity Framework ,高效的 NavigationProperty.OfType 查询

c# - Web API 无法使用 utf-16 编码的 XML 为 POST 绑定(bind)模型

c# - 使用 LINQ 或 Lambda 从列表中删除实例?

c# - 将 IQueryable where 子句从 DTO 映射到实体