For our exercises (using Windows forms and classes), we have been asked to create a list of classes (different kind of Animals ex. Dog, cat, cow etc) and make them appear in a listbox sorted by alphabetical order. To do that, we used a variable called AnimalName which is a name for the Animal. Now I want to sort these classes by AnimalName but how can I do that? Here is the code:
List<NamedAnimal> animalist = new List<NamedAnimal>
{
new Bear("Angry Joe") { }, new Cat("Snow White") { }, new Chicken("Henifer Aniston") { }, new Cow("Lolita") { }, new Dog("Vigi the loon") { },
new Duck("Ronald Duck") { }, new Horse("Shadow") { }, new Kangaroo("Boxer") { }, new Moose("Mickey Moose") {}
};
private void AnimalForm_Load(object sender, EventArgs e)
{
foreach (NamedAnimal animal in animalist)
{
listBoxAnimal.Items.Add(animal.AnimalName);
}
}
I know that after the foreach statement, I must write a line of code that takes the animals' names from the listbox and presents them in an alphabetical order. I also want to write a line of code that stores alphabetically the classes in my list by using the animal's name. (Angry Joe, Boxer, e.t.c.). How do I write it? I tried something like:
animalist.Sort();
after the foreach statement but I get an unhandled exception.
how do I sort the classes in the list alphabetically using the AnimalName???