How to sort a List in C#?
How to sort a List 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 in C#:
Sort()
method.OrderBy()
method from LINQ.Using the
Sort()
methodThe
Sort()
method takes a delegate as its parameter. The delegate is a function that takes two elements of the same type and returns an integer value indicating their relative order. The following code sorts a list of integers in ascending order:C#
In this code, the delegate is an anonymous method that compares two integers. The
CompareTo()
method returns an integer value indicating the relative order of the two integers. A value of -1 means that the first integer is less than the second integer, a value of 0 means that the two integers are equal, and a value of 1 means that the first integer is greater than the second integer.Using the
OrderBy()
method from LINQThe
OrderBy()
method from LINQ is a more concise way to sort a list. 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 of integers as the previous example using theOrderBy()
method:C#
In this code, the lambda expression specifies that the list should be sorted by the
x
property of theint
objects.Which method you use to sort a list 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.