【问题标题】:How to Sort one collection based on another one and other condition如何根据另一个和其他条件对一个集合进行排序
【发布时间】:2021-08-15 06:43:32
【问题描述】:

我有一个要排序的列表:

List<string> temp = {
    "Mina 1", "Mina 2", 
    "Planning 3", "Planning 2", "Planning 1", "Planning 4", 
    "Kira 2", "Kira 1"};

要排序的列表:

// Sort items based on the following order of name
List<string> listToSort= {"Planning", "Mina", "Kira" };

我正在尝试根据 listToSort 和数字增加对 temp 进行排序

预期结果:

List<string> temp = {
    "Planning 1", "Planning 2", "Planning 3", "Planning 4",
    "Mina 1", "Mina 2",  
    "Kira 1", "Kira 2"};

【问题讨论】:

  • 您在尝试时会遇到哪些问题?目前尚不清楚您在哪里需要帮助。

标签: c# linq lambda


【解决方案1】:

由于这些是列表,您可以使用FindIndexStartsWith 的组合:

var result = temp
    .OrderBy(t => listToSort.FindIndex(s => s.StartsWith(t)))
    .ThenBy(t => t);

【讨论】:

    【解决方案2】:

    虽然不是最有效的,但一种选择是使用SelectMany

    var sorted = listToSort.SelectMany(sortKey => temp.Where(t => t.StartsWith(sortKey)).OrderBy(s => s));
    

    对于listToSort中的每个字符串,SelectManytemp中查找所有相关字符串并按它们排序。

    如果需要自然排序(所以“Kira 11”会排在“Kira 9”之后),可以添加比较器,例如Natural Sort Order in C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2015-10-18
      • 2012-09-14
      相关资源
      最近更新 更多