C# Example: Sorting a list of Person objects by age - Biz Tech

C# Example: Sorting a list of Person objects by age

Listen
using System;
using System.Collections.Generic;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "John", Age = 30 },
            new Person { Name = "Jane", Age = 25 },
            new Person { Name = "Bob", Age = 35 }
        };

        people.Sort((p1, p2) => p1.Age.CompareTo(p2.Age));

        foreach (Person person in people)
        {
            Console.WriteLine(person.Name + " " + person.Age);
        }
    }
}

This example creates a list of Person objects and sorts them by age using a custom comparison function. The following steps are performed:

  1. Define the Person class with Name and Age properties.
  2. Create a list of Person objects and add three items to it.
  3. Call the Sort() method on the list, passing in a custom comparison function that compares the Age properties of the two Person objects.
  4. Iterate over the sorted list and output the Name and Age properties of each Person object using Console.WriteLine().