Lexicographically sorted list of lists of strings

前端 未结 4 1570
轻奢々
轻奢々 2021-01-19 05:39

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:



        
相关标签:
4条回答
  • 2021-01-19 06:11

    You can also use

    myList = myList.OrderBy(arr => arr[0])
                    .ThenBy(arr => arr[1])
                    .ThenBy(arr => arr[2])
                    .ToList();
    
    0 讨论(0)
  • 2021-01-19 06:21

    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

    0 讨论(0)
  • 2021-01-19 06:28

    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.

    0 讨论(0)
  • 2021-01-19 06:30

    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();
    
    0 讨论(0)
提交回复
热议问题