Lexicographically Sorted List of String Lists

I am currently trying to implement code to generate frequent sequences. In doing so, I need to get the list in place of the list of row lists 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 result I need is:

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

I tried to use myList.Sort(), but he picked up System.InvalidOperationException. I am not so good at LINQ, so I have not used anything like this.

+4
source share
4 answers

What about:

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

The trick is to sort according to the string created by concatenating each item in the child list.

+2
source

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

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

+1

You can try under the 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();
0
source

You can also use

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

Source: https://habr.com/ru/post/1675599/


All Articles