-2

I have list of objects with different values int's, double's, string's. In this case i want to sort list of objects by "name". I done it for int's but can't by string.

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

public void CreateMammal()                             // obj creating method
    {        
        Console.WriteLine("Podaj Imie: ");
        name = Console.ReadLine();
        Console.WriteLine("Podaj Wiek: ");
        age = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Podaj Wagę: ");
        weigth = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Podaj Kolor Futra: ");
        furColour = Console.ReadLine();
        ToString();                    
     }
.
.
.
List<Animal> animals = new List<Animal>();     // list declaration
.
.
.
Mammal mammal = new Mammal();
mammal.CreateMammal();
Console.WriteLine("\n\nTwoj ssak:\n" + 
mammal.ToString());
animals.Add(mammal);
.
.
.

//animals.Sort((x, y) => x."name" - y."name");  // algorytm sortowania
//printAnimals(animals);

animals.Sort();                   // here we go with problem

foreach (string value in animals)
{
Console.WriteLine(value);
}
.
.
.
 public static void printAnimals(List<Animal> animals) 
    {
        foreach (var animal in animals)
        {
            Console.WriteLine(animal.ToString());
        }
    }

1 Answers1

0

Well you can use Linq OrderBy() probably to sort by name property like (under System.Linq namespace)

var orderedAnimals = animals.OrderBy(x => x.name).ToList(); 
Rahul
  • 76,197
  • 13
  • 71
  • 125