8

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?

1

4 Answers 4

14

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
Sign up to request clarification or add additional context in comments.

Comments

5

You can do:

var newList = list.OrderBy(r => r[0])
                  .ThenBy(r => r[1])
                  .ThenBy(r => r[2])
                  .ToList();

This will assume that your List will have an element of string array with a length of at least 3 items. This will first sort the List based on First item of the array, Animal, Then Bread and then Name.

If your List is defined as:

List<string[]> list = 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"}
                                            };

A better way to approach that problem would be to have custom class, with Type, Bread and Name as property and then use that instead of string[]

You can define your own class:

public class Animal
{
    public string Type { get; set; }
    public string Bread { get; set; }
    public string Name { get; set; }

    public Animal(string Type, string Bread, string Name)
    {
        this.Type = Type;
        this.Bread = Bread;
        this.Name = Name;
    }
}

and then define your List<Animal> like:

List<Animal> animalList = new List<Animal>
{
    new Animal("Dog", "Golden Retriever", "Rex"),
    new Animal("Cat", "Tabby", "Boblawblah"),
    new Animal("Fish", "Clown", "Nemo"),
    new Animal("Dog", "Pug", "Daisy"),
    new Animal("Cat", "Siemese", "Wednesday"),
    new Animal("Fish", "Gold", "Alaska"),
};

Later you can get the sorted list like:

List<Animal> sortedList = animalList
                            .OrderBy(r => r.Type)
                            .ThenBy(r => r.Bread)
                            .ToList();

If you want, you can implement your own custom sorting, see: How to use the IComparable and IComparer interfaces in Visual C#

5 Comments

OK, I must have done some horrible mistake, but please point it out.
It's similar to my answer so why i didn't get downvotes? I am shocked ;)
@TimSchmelter, I posted after 2 minutes of your answer, But I never saw your answer before posting it. I believe people don't like duplicate answers and importantly you are popular :P
@Habib: Well, let's set that straight. +1. Tim too of course ;)
+ another 1 for the "better way to approach it".
1

For a more simple or well-rounded approach, you could use bubble sort to sort your list of string arrays, depending on the element you wish to sort by. For example:

static void Main(string[] args)
{
    List<string[]> animalCount = new List<string[]>() 
    { 
        new string[] { "Dogs: ", "12" }, 
        new string[] { "Cats: ", "6" }, 
        new string[] { "Monkeys: ", "15" },
        new string[] { "Fish: ", "26" },
        new string[] { "Dinosaurs: ", "0" },
        new string[] { "Elephants: ", "2" }
    };

    List<string[]> sortedAnimalCount = SortedCountList(animalCount);

    foreach (string[] item in sortedAnimalCount)
    {
        Console.WriteLine(item[0] + "" + item[1]);
    }

    Console.ReadKey();
}

static List<string[]> SortedCountList(List<string[]> countList)
{
    string[][] charArray = countList.ToArray();

    int ItemToSortBy = 1; // Sorts list depending on item 2 of each string array
    int numItems = charArray.Length;
    bool IsSwapping = true;
    int i = 0;

    while (i < (numItems - 1) && IsSwapping == true)
    {
        IsSwapping = false;

        for (int j = 0; j < numItems - i - 1; j++) // Bubble sort the List in reverse
        {
            if (Convert.ToInt32(charArray[j][ItemToSortBy]) < Convert.ToInt32(charArray[j + 1][ItemToSortBy]))
            {
                string[] temp = charArray[j];
                charArray[j] = charArray[j + 1];
                charArray[j + 1] = temp;
                IsSwapping = true;
            }
        }

        i += 1;
    }

    return charArray.ToList();
}
  • Outputs: Fish: 26 Monkeys: 15 Dogs: 12 Cats: 6 Elephants: 2 Dinosaurs: 0

2 Comments

I can see that this question is 6 years old and already has an answer that was accepted as correct. It's always useful if you know how to implement a search algorithm from scratch, so well done for that. If you're trying to build up your StackOverflow reputation score I would suggest trying to find questions that you are knowledgable about using the search facility, or just look at newer questions using the Week or Month buttons. As soon as somebody likes or accepts one of your answers, you'll build up reputation points and badges in no time.
Thanks for the constructive advice Mark!
0

If you can use LINQ, you can do something like:

myanimals = myanimals.OrderBy(a => a[0]).ThenBy(a => a[1]).ToList();

Or the same in query:

myanimals = (from a in animals order by a[0], a[1] select a).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.