int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 }; var sortedNumbers = numbers.OrderBy(num => num); foreach (var num in sortedNumbers) { Console.WriteLine(num); }
ListIn this example, a list of Student objects is sorted first by age and then by name. The ThenBy method is used to specify the secondary sorting criteria. The OrderBy method is a part of the System.Linq package library.students = new List () { new Student() { Name = "John", Age = 20 }, new Student() { Name = "Alice", Age = 19 }, new Student() { Name = "Bob", Age = 20 }, new Student() { Name = "David", Age = 18 } }; var sortedStudents = students.OrderBy(s => s.Age).ThenBy(s => s.Name); foreach (var student in sortedStudents) { Console.WriteLine(student.Name + " " + student.Age); }