Sort list of string arrays c#

arrays, c#, list, sorting

Solution

You can use LINQ:

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

Your sample:

List<string[]> animalList = new List<String[]>{ 
            new []{"Dog", "Golden Retriever", "Rex"},
            new []{"Cat", "Tabby", "Boblawblah"},
            new []{"Fish", "Clown", "Nemo"},
            new []{"Dog", "Pug", "Daisy"},
            new []{"Cat", "Siemese", "Wednesday"},
            new []{"Fish", "Gold", "Alaska"}
        };

Result:

-       [0] {string[3]} string[]
        [0] "Cat"   string
        [1] "Siemese"   string
        [2] "Wednesday" string
-       [1] {string[3]} string[]
        [0] "Cat"   string
        [1] "Tabby" string
        [2] "Boblawblah"    string
-       [2] {string[3]} string[]
        [0] "Dog"   string
        [1] "Golden Retriever"  string
        [2] "Rex"   string
-       [3] {string[3]} string[]
        [0] "Dog"   string
        [1] "Pug"   string
        [2] "Daisy" string
-       [4] {string[3]} string[]
        [0] "Fish"  string
        [1] "Clown" string
        [2] "Nemo"  string
-       [5] {string[3]} string[]
        [0] "Fish"  string
        [1] "Gold"  string
        [2] "Alaska"    string

Problem

I have a list of string arrays, where the arrays are formatted as [Animal, Breed, Name]: ``` { ["Dog", "Golden Retriever", "Rex"], ["Cat", "Tabby", "Boblawblah"], ["Fish", "Clown", "Nemo"], ["Dog", "Pug", "Daisy"], ["Cat", "Siemese", "Wednesday"], ["Fish", "Gold", "Alaska"] } ``` How would I sort this list so that it was arranged alphabetically by "Animal", and then "Breed"? i.e.: ``` { ["Cat", "Siamese", "Boblawblah"], ["Cat", "Tabby", "Wednesday"], ["Dog", "Golden Retriever", "Rex"], ["Dog", "Pug", "Daisy"], ["Fish", "Clown", "Nemo"], ["Fish", "Gold", "Alaska"] } ``` I am currently trying: ``` animalList.Sort((s, t) => String.Compare(s[0], t[0])); ``` But that is not sorting the second column correctly. In addition to sorting by the first two columns alphabetically, how would I then add in the third column?

Original source

Related problems