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?
To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.
C Sort String in Ascending Order Receive any string using gets() function. Get the length of string using strlen() function of string. h library and initialize it to any variable say len. Now create a for loop that runs from 0 to one less than the string length.
Below is the simple C program that will accept the character string from the user, calculates the length of the string and performs sorting operation on the string. The program will sort the character array in ascending order and display the result string (character array).
Sort an Array of string using Selection sort in C++ In each emphasis of determination sort, the base component from the unsorted subarray is picked and moved to the arranged subarray.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With