The OrderBy
operator is a LINQ query operator that sorts the elements of a sequence in ascending order according to a key. The key is specified by a function that takes an element of the sequence as input and returns a value that is used to determine the sort order.
Here are some examples of how you might use the OrderBy
operator in C#:
Example 1: Sorting a list of integers in ascending order:
1 2 3 4 | List<int> numbers = new List<int> { 3, 1, 4, 2, 5 }; var sortedNumbers = numbers.OrderBy(n => n); |
Example 2: Sorting a list of strings in alphabetical order:
1 2 3 4 | List<string> words = new List<string> { "cherry", "apple", "banana" }; var sortedWords = words.OrderBy(w => w); |
Example 3: Sorting a list of objects by a specific property:
1 2 3 4 | List<Person> people = GetPeople(); var sortedPeople = people.OrderBy(p => p.LastName); |
Example 4: Sorting a list of objects by multiple properties:
1 2 3 4 | List<Employee> employees = GetEmployees(); var sortedEmployees = employees.OrderBy(e => e.Department).ThenBy(e => e.Salary); |
Example 5: Sorting a list of complex objects by a specific property, and then flattening the result:
1 2 3 4 5 6 | List<Department> departments = GetDepartments(); var sortedEmployees = departments.SelectMany(d => d.Employees) .OrderBy(e => e.Name) .Select(e => e.Name); |
In these examples, the OrderBy
operator is used to sort the elements of a sequence in ascending order according to a key. The key is specified by a function that takes an element of the sequence as input and returns a value that is used to determine the sort order.
In the first example, the OrderBy
operator is used to sort a list of integers in ascending order. In the second example, the OrderBy
operator is used to sort a list of strings in alphabetical order. In the third example, the OrderBy
operator is used to sort a list of Person
objects by the LastName
property. In the fourth example, the OrderBy
operator is used in conjunction with the ThenBy
operator to sort a list of Employee
objects first by the Department
property and then by the Salary
property. In the fifth example, the SelectMany
operator is used to flatten a nested list of employees within departments, OrderBy
operator is used to sort the list by the Name
property, and the Select
operator is used to create a new sequence of employee names.
It’s worth noting that OrderBy
operator returns an IOrderedEnumerable<T>
object which is a sequence that is sorted by the key and it can use the ThenBy
operator to specify additional sorting criteria.
[…] OrderBy: Sorts the elements of a sequence in ascending or descending order […]