【问题标题】:Lexicographically sorted list of lists of strings按字典顺序排序的字符串列表列表
【发布时间】:2017-04-25 09:58:13
【问题描述】:

目前,我正在尝试实现一个代码来生成频繁的序列。在这样做时,我需要得到一个就地排序的字符串列表,如下所示:

List<List<string>> myList = new List<List<string>>();
List<string> input1 = new List<string>() {"a", "b", "d"};
List<string> input2 = new List<string>() {"a", "b", "c"};
myList.Add(input1);
myList.Add(input2);

我需要的输出是:

myList = {{"a","b","c"},{"a","b","d"}};

我曾尝试使用myList.Sort(),但它引发了System.InvalidOperationException。 我不太擅长 LINQ,所以我没有使用过类似的东西。

【问题讨论】:

  • 堆栈跟踪和发生异常的行可能会有所帮助。

标签: c# list sorting


【解决方案1】:

怎么样:

myList = myList.OrderBy(s => string.Join(string.Empty, s)).ToList();

诀窍是根据子列表的每个元素串联而成的字符串进行排序。

【讨论】:

    【解决方案2】:

    如果你想用Sort()解决你可以使用这种方法

    myList.Sort((x, y) => x.Zip(y,(l1,l2) => string.Compare(l1,l2)).FirstOrDefault(c => c != 0));
    

    否则,我会将所有项目合并为一个 string 并进行比较。

    这样效率较低,因为必须先创建字符串对象。

     myList = myList.OrderBy(string.Concat).ToList();
    

    示例:https://dotnetfiddle.net/1VmohI

    【讨论】:

      【解决方案3】:

      你可以试试下面的代码:

              List<string> input1 = new List<string>() { "a", "b", "d" };
              List<string> input2 = new List<string>() { "a", "b", "c" };
      
              //Instead of adding input as List<string>, add it as string
              string delimiter = ",";
              var input1Str = input1.Aggregate((i, j) => i + delimiter + j);
              var input2Str = input2.Aggregate((i, j) => i + delimiter + j);
      
              var myListStr = new List<string>();
              myListStr.Add(input1Str);
              myListStr.Add(input2Str);
      
              myListStr.Sort();
              //Now you can convert it into List<List<string>>
              List<List<string>> myList = myListStr.Select(x => x.Split(',').ToList()).ToList();
      

      【讨论】:

        【解决方案4】:

        你也可以使用

        myList = myList.OrderBy(arr => arr[0])
                        .ThenBy(arr => arr[1])
                        .ThenBy(arr => arr[2])
                        .ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-14
          • 2014-06-19
          • 1970-01-01
          • 2013-05-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多