Methods Ordering

Methods for ordering the elements

OrderBy() method

OrderBy() sorts the elements in the source sequence based on a key value. The examples below demonstrate how this works

List<string> strings = new List<string> 
{ "first", "then", "and then", "finally" };

// Sort the strings by their length
// Will contain { "then", "first", "finally", "and then" }
IEnumerable<string> result = strings.OrderBy(str => str.Length);

ThenBy() method

We can have two level ordering as shown below

class Program
{
    class Student
    {
        public string Name { get; } //Property
        public string City { get; }
        
        public Student(string name, string city)
        {
            Name = name;
            City = city;
        }
    }
    
    static void Main()
    {
        //Object initialization syntax
        List<Student> students = new List<Student>()
        {
            new Student("Sam","Mysore"),
            new Student("Ted","Delhi"),
            new Student("Sam","Bangalore"),            
            new Student("Raj","Mumbai"),
            new Student("Adhin","Hyderabad"),
            new Student("Raj","Indore"),            
            new Student("Bhuvan","Chennai"),
            new Student("Sam","Banaras"),
        };

    var res = students.OrderBy(s => s.Name).ThenBy(s => s.City);
    
    foreach (var s in res)
        Console.WriteLine(s.Name + " " + s.City);
    
    Console.ReadKey();
    }
}

There is no Sort()

If you want to sort the elements within a sequence, but we achieve the same using the query below

List<string> strings = new List<string>()
{ "first", "then", "and then", "finally" };

// Sort the strings in alphabetical order
// Will contain { "and then", "finally", "first", "then" }
IEnumerable<string> result = strings.OrderBy(str => str); //strange?!

foreach (string str in result)
    Console.WriteLine(str);

Can you try these for an Employee(int id, string name, int age) object?

Last updated