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:
- Define the
Person
class withName
andAge
properties.- Create a list of
Person
objects and add three items to it.- Call the
Sort()
method on the list, passing in a custom comparison function that compares theAge
properties of the twoPerson
objects.- Iterate over the sorted list and output the
Name
andAge
properties of eachPerson
object usingConsole.WriteLine()
.