Listnumbers = new List { 5, 1, 8, 2, 10 }; var sortedNumbers = numbers.OrderBy(n => n); foreach (var num in sortedNumbers) { Console.Write(num + " "); } // Output: 1 2 5 8 10
Listnames = new List { "John", "Mary", "Bob", "Alice" }; var sortedNames = names.OrderBy(n => n.Length); foreach (var name in sortedNames) { Console.Write(name + " "); } // Output: Bob John Mary Alice
ListThis example sorts a list of custom objects (Person) based on their age property and prints it to the console along with their name. The OrderBy method is part of the System.Linq library in C#.people = new List { new Person("John", 30), new Person("Mary", 25), new Person("Bob", 40) }; var sortedPeople = people.OrderBy(p => p.Age); foreach (var person in sortedPeople) { Console.WriteLine(person.Name + " (" + person.Age + ")"); } // Output: Mary (25) John (30) Bob (40) class Person { public string Name { get; set; } public int Age { get; set; } public Person(string name, int age) { Name = name; Age = age; } }