How to sort object array by specific property in C#?

0

 


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#:

using System;
using System.Linq;

namespace ObjectArraySort
{
    class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public int EmployeeAge { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee[] employees = new Employee[]
            {
                new Employee { EmployeeId = 1, EmployeeName = "John Doe", EmployeeAge = 30 },
                new Employee { EmployeeId = 2, EmployeeName = "Jane Doe", EmployeeAge = 25 },
                new Employee { EmployeeId = 3, EmployeeName = "Jim Smith", EmployeeAge = 35 },
                new Employee { EmployeeId = 4, EmployeeName = "Emily Johnson", EmployeeAge = 28 }
            };

            var sortedEmployees = employees.OrderBy(e => e.EmployeeAge);
            Console.WriteLine("Sorted Employees by Age:");
            foreach (var employee in sortedEmployees)
            {
                Console.WriteLine("Employee Id: " + employee.EmployeeId + ", Employee Name: " + employee.EmployeeName + ", Employee Age: " + employee.EmployeeAge);
            }
        }
    }
}





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.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !