c# - 在 linq c# 中使用 where 条件对列表进行排序

标签 c# list linq

我有一个 List类型 Test其中有 4 propertiesList需要根据一些特定条件进行排序。下面是propertiesclass Test以及示例数据。

class Test
{
    int order;
    string value;
    string dept;
    //..... and some others
}

示例 json:

[
   {
      "order":3,
      "value":"ABC",
      "dept":"A"
   },
   {
      "order":2,
      "value":"XYZ",
      "dept":"A"
   },
   {
      "order":1,
      "value":"ABC2",
      "dept":"P"
   },
   {
      "order":4,
      "value":"XYZ2",
      "dept":"P"
   },
   {
      "order":6,
      "value":"ABC3",
      "dept":"Z"
   },
   {
      "order":5,
      "value":"XYZ3",
      "dept":"Z"
   },
]

以上json数据加载到一个 List<Test> .

我的要求是对上面的列表进行排序,就像首先对带有 dept=P 的项目进行排序一样, 然后 dept=A然后 dept=Z第二个排序标准是order .

我试过 OrderBy(x=>x.dept).ThenBy(x=>x.order)但输出不是预期的。

有没有办法指定 dept应该首先出现在列表中。

作为解决方法,我拆分了 List进入多个列表,然后 merge他们在sorting之后,但这不是我猜想的最佳解决方案。

对此我们还有其他更好的优化解决方案吗?

最佳答案

好吧,你可以用你的排序规则创建一个列表:

var orderOfDepts = new List<string> { "P", "A", "Z" };

并使用该列表中元素的索引进行排序:

var sortedList = myList.OrderBy(x=> orderOfDepts.IndexOf(x.dept)).ThenBy(x=> x.order).ToList();

附言 如果 sortedList 集合不是太大,此解决方案很好,但如果它很大或者您在 orderOfDepts 列表中有很多排序规则,那么您可能希望降低整体复杂性这个算法从 > O(N2) 到接近 O(N*logN) 的东西。

为此我们可以利用 Dictionary 的快速查找:

int o;
var orderOfDepts = new Dictionary<string, int> 
{
   { "P", 0 },
   { "A", 1 },
   { "Z", 2 }
};

var sortedList = myList.OrderBy(x => orderOfDepts.TryGetValue(x.dept, out o) ? o : int.MaxValue)
                       .ThenBy(x=> x.order)
                       .ToList();

这里我们尝试通过关键字x.dept 从字典中获取元素。如果我们没有找到任何东西,我们将该项目放在列表的末尾,否则我们使用字典中的值进行排序。

Dictionary 的查找是 O(1) 的,因此它将大大提高性能,但会花费构造字典对象所需的时间。对于少数元素,这样做是不可取的,第一种解决方案更好,但对于大量数据,这种解决方案是好的。

关于c# - 在 linq c# 中使用 where 条件对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57671945/

相关文章:

c# - 如何在重新启用后保持 ToggleButton 状态

c# - 将固定长度的字符串写到文件上吗?

c# - 从 Python 运行 .NET COM 程序集。程序集 dll 的 Python 路径?

python - 在python中的列表中查找元组之间的公共(public)元素

c# - 如何连接两个表,其中条件 'Where' 与与第一个表关联的第三个表相关

c# - WCF Web 服务返回 json 格式数据

c#如何将信息添加到高分类

python - 如何将元组列表转换为多个列表?

c# - DbFunctions DiffDays 给出了错误的答案

c# - linq按子字符串对数组中的字符串进行排序