1

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???

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
SoftDev30_15
  • 463
  • 7
  • 20
  • 1
    Possible duplicate of [How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – DeanOC Mar 06 '16 at 18:51
  • I saw that thread before I opened my own, but I saw that the person sorting his classes in the list, wanted to use numbers instead of sorting them alphabetically... I have the impression that the code and the functions behind the listing of the two is very different and wanted an opinion. – SoftDev30_15 Mar 11 '16 at 12:48

3 Answers3

4

You can sort a List<T> using OrderBy and OrderByDescending methods and then set the sorted list as DataSource of your ListBox:

listBoxAnimal.DataSource= animalist.OrderBy(x => x.AnimalName).ToList();
listBoxAnimal.DisplayMember = "AnimalName"

Also by setting a field like AnimalName as DisplayMember of the ListBox you tell the control to show that field of your class as items text.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • I see a lamda expression up here... does that mean that I need to work with interface (IComparable) to do this??? – SoftDev30_15 Mar 11 '16 at 12:42
  • No, `AnimalName` is string. – Reza Aghaei Mar 11 '16 at 12:43
  • Yes, but it is a variable within a class that contains other variables as well... (number of legs, species e.t.c.)... And I wish to sort the classes and all of their components using the AnimalName... And show them on the screen too... – SoftDev30_15 Mar 12 '16 at 11:42
  • The code sample in the answer exactly does it. Try it and let me know if you have any question about the answer :) – Reza Aghaei Mar 12 '16 at 11:45
  • `animalist.OrderBy(x => x.AnimalName)` means sorting animallist based on `AnimalName` property of list items. – Reza Aghaei Mar 12 '16 at 11:46
  • I posted my reply below... Unfortunately lamda expressions were not the solution for the particular code. Due to health reasons I delayed replying and I apologize. This topic can be closednow. Thank you for your suggestions. – SoftDev30_15 Apr 08 '16 at 17:17
  • 1
    Thank you for your response, I prefer to use linq because it's more simple and flexible. Probably you had some tiny mistakes applying the code. No problem. Hope you feel better soon :) – Reza Aghaei Apr 08 '16 at 17:58
  • True... linq seems to be easier and more flexible... But the code I had to work with was not entirely my own... In fact I had to add things without altering the basic parts... and that's why I had to do things with IComparable Interface instead of Linq... Anyway thank you for the wishes and I thank everyone for your suggestions!! – SoftDev30_15 Apr 10 '16 at 23:09
0

To get the names sorted, you can try sorting on Property AnimalName. Also, you can define the DataSource for the ListBox using DataSource property.

var animalNameSortedList = animallist.Select(x => x.AnimalName).ToList();
animalNameSortedList.Sort();
listBoxAnimal.DataSource = animalNameSortedList;
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
0

I followed the suggestions with the lamda expressions but they didn't seem to work. But I did find another way with IComparable so I am posting it so that everyone can have the alternative.

The class NamedAnimal goes like this:

class NamedAnimal : Animal, IComparable<NamedAnimal>
{
    public string AnimalName { get; set; }

    public NamedAnimal(): base ()
    {
       //first constructor with the variables inherited from class Animal
    }

    public NamedAnimal() : base()
    {
        //2nd constructor with the variables inherited + the AnimalName
    }

    public virtual string GetNotes()
    {
        return "No notes available";
    }

   public int CompareTo(NamedAnimal otherAnimalName)
    {

        return AnimalName.CompareTo(otherAnimalName.AnimalName);

    }   
}

and finally in Form load:

private void AnimalForm_Load(object sender, EventArgs e)
    {
        //solution with multiple inheritance comparer

        animalist.Sort();

        foreach (NamedAnimal animal in animalist)
        {
            listBoxAnimal.Items.Add(animal.AnimalName);

        }

    }

It worked!! I categorized the list of animals alphabetically based on their names! So that would be a 2nd solution apart from lamda expressions. Thank you for your help, since I will need your suggestions in the future. You can mark the thread as solved.

SoftDev30_15
  • 463
  • 7
  • 20