int[] numbers = { 4, 9, 3, 2, 7, 8 }; var sortedNumbers = numbers.OrderBy(n => n); foreach (var num in sortedNumbers) { Console.WriteLine(num); }
ListIn this example, we have a list of Person objects, each with a Name and Age property. We use the OrderBy method to sort the list in ascending order based on the Age property. The lambda expression `p => p.Age` specifies the key on which to sort the list. The sortedPeople variable now contains the sorted sequence, which we print out to the console using a foreach loop to display each person's name and age. The System.Linq namespace is part of the .NET Framework, which is a package library provided by Microsoft.people = new List { new Person { Name = "Alice", Age = 25 }, new Person { Name = "Bob", Age = 30 }, new Person { Name = "Charlie", Age = 20 } }; var sortedPeople = people.OrderBy(p => p.Age); foreach (var person in sortedPeople) { Console.WriteLine($"{person.Name} ({person.Age})"); }