📜  OrderBy c# (1)

📅  最后修改于: 2023-12-03 15:33:20.510000             🧑  作者: Mango

OrderBy in C#

OrderBy is a LINQ method used in C# to sort a sequence of elements based on a specified key in ascending order. In this article, we will explore how to use OrderBy method in C# with a brief example.

Syntax

The syntax for OrderBy method is as follows,

public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource,TKey>(
    this System.Collections.Generic.IEnumerable<TSource> source,
    System.Func<TSource,TKey> keySelector
)
Parameters
  • source: This parameter of IEnumerable<T> type represents the input sequence that needs to be sorted.
  • keySelector: This parameter of Func<T,TKey> type represents the function that extracts the key for each element in the sequence corresponding to which the sorting operation will be performed.
Return Value

The OrderBy method returns an ordered sequence of elements based on the specified key in ascending order.

Example

Let's consider a list of employees and we want to sort them based on their age.

List<Employee> employees = new List<Employee>()
{
    new Employee { Id = 1, Name = "Alice", Age = 30 },
    new Employee { Id = 2, Name = "Bob", Age = 25 },
    new Employee { Id = 3, Name = "Charlie", Age = 40 }
};

var sortedEmployees = employees.OrderBy(emp => emp.Age);

foreach (var emp in sortedEmployees)
{
    Console.WriteLine($"Id: {emp.Id}, Name: {emp.Name}, Age: {emp.Age}");
}

Output:

Id: 2, Name: Bob, Age: 25
Id: 1, Name: Alice, Age: 30
Id: 3, Name: Charlie, Age: 40

In the above example, we have used OrderBy method to sort a list of employees based on their age. We have used lambda expression emp => emp.Age to extract the age of each employee as a key to perform the sorting operation.

Conclusion

In this article, we have learned how to use OrderBy method in C# to sort a sequence of elements based on a specified key in ascending order. We have also explored the syntax, parameters, and return value of the OrderBy method.