Lexicographically sorted list of lists of strings

ε祈祈猫儿з 提交于 2020-08-19 14:03:30

问题


Currently, I am trying to implement a code to generate frequent sequences. In doing so I need to get an in-place sort of a list of lists of strings as follows:

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);

The output that I need is:

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

I have tried to use myList.Sort() but it raised a System.InvalidOperationException. I am not that good with LINQ so I haven't used anything of the sort.


回答1:


How about :

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

The trick is to sort according to the string made by the concatenation of each element of the child list.




回答2:


If you want to solve with Sort() you may use this approach

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

Otherwise I would concartenate all items into a single string and compare those.

This is less efficient because the string objects have to be created first.

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

Sample: https://dotnetfiddle.net/1VmohI




回答3:


You can try below code:

        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:


You can also use

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


来源:https://stackoverflow.com/questions/43607446/lexicographically-sorted-list-of-lists-of-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!