How to Sort a List by a property in the object in c#?
How to Sort a List<T> by a property in the object in c#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
18-Aug-2023There are two ways to sort a list by a property in an object in C#:
Sort()
method with aComparison<T>
delegate.OrderBy()
method from LINQ.Using the
Sort()
method with aComparison<T>
delegateThe
Sort()
method takes aComparison<T>
delegate as its parameter. TheComparison<T>
delegate is a function that takes two elements of typeT
and returns an integer value indicating their relative order. The following code sorts a list ofPerson
objects by their age:C#
In this code, the
Comparison<T>
delegate is an anonymous method that compares the ages of twoPerson
objects. TheCompareTo()
method returns an integer value indicating the relative order of the two objects. A value of -1 means that the first object is less than the second object, a value of 0 means that the two objects are equal, and a value of 1 means that the first object is greater than the second object.Using the
OrderBy()
method from LINQThe
OrderBy()
method from LINQ is a more concise way to sort a list by a property. TheOrderBy()
method takes a lambda expression as its parameter. The lambda expression specifies the property that the list should be sorted by. The following code sorts the same list ofPerson
objects as the previous example using theOrderBy()
method:C#
In this code, the lambda expression specifies that the list should be sorted by the
Age
property of thePerson
objects.Which method you use to sort a list by a property depends on your preference. The
Sort()
method is more flexible, as you can use it to sort a list by any property. However, theOrderBy()
method is more concise and easier to read.