In C#, you can sort an array of objects by a specific property by using the Linq
method OrderBy
. The OrderBy
method sorts the elements of a collection in ascending order based on a specified key. To sort an object array by a specific property, you need to provide a lambda expression
that specifies the property to be used as the key for the sort operation.
Here's an example that demonstrates how to sort an object array by a specific property in C#:
In this example, we declared a class named Employee
that contains three properties: EmployeeId
, EmployeeName
, and EmployeeAge
. We then created an array of Employee
objects named employees
and assigned some values to it.
Next, we used the Linq
method OrderBy
to sort the employees
array by the EmployeeAge
property. The OrderBy
method takes a lambda expression
as an argument that specifies the property to be used as the key for the sort operation. In this case, we used the EmployeeAge
property. The OrderBy
method returns an ordered IEnumerable
that we stored in the sortedEmployees
variable.
Finally, we used a foreach
loop to print the sorted array of Employee
objects on the console. The output of the program will show the sorted Employee
objects by their EmployeeAge
property in ascending order.
In conclusion, sorting an object array by a specific property in C# is a simple and straightforward task that can be achieved by using the Linq
method OrderBy
. All you need to do is to provide a lambda expression
that specifies the property to be used as the key for the sort operation, and the OrderBy
method will take care of the rest.