Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 81.7k

how to use Sort() with two levels (without using Linq)?

Aug 25 2022 4:27 PM

Hi
This code sorts by age. But is it possible to sort by age and then by name (without using Linq!).
I know how to do using Linq (var sort1 = le.OrderBy(x => x.Age).ThenBy(x => x.Name);), but i wonder whether it's possible to do the same with Sort().

Now i get this:
Joe USA 32
Bill USA 32
Bob UK 36

What i want is:
Bill USA 32
Joe USA 32
Bob UK 36

Thanks
V

using System;
using System.Collections.Generic;

class MyClass
{
    public string Name;
    public int Age; 
    public string Country;
}

class Program
{
    static void Main(string[] args)
    {
        List<MyClass> t = new List<MyClass>();
        t.Add(new MyClass() { Name = "Bob", Age = 36, Country = "UK" });
        t.Add(new MyClass() { Name = "Joe", Age = 32, Country = "USA" });
        t.Add(new MyClass() { Name = "Bill", Age = 32, Country = "USA" });
        t.Sort((x, y) => x.Age.CompareTo(y.Age));
        foreach (MyClass x in t)
            Console.WriteLine(x.Name + " " + x.Country + ", " + x.Age);
    }
}


Answers (4)