I have a class called Person which contains a property LastName, which reflects a string cooresponding to the Person's last name.
I created a List as follows:
var People = List<Person>
What I would like to do is sort the people by their LastName property in alphabetical order.
After looking at some examples, I've tried
People = People.OrderBy(p => p.LastName);
But it does not work.
Using LINQ, you'd need to convert the results back into a List<Person>
:
People = People.OrderBy(p => p.LastName).ToList();
Since OrderBy
returns an IOrderedEnumerable<T>
, you need the extra call ToList()
to turn this back into a list.
However, since you effectively want an in-place sort, you can also use List<T>.Sort
directly:
People.Sort((p1, p2) => p1.LastName.CompareTo(p2.LastName));
The easiest is using ToList():
People = People.OrderBy(p => p.LastName).ToList();
You need the ToList
to create a new ordered List<Person>
Another option to sort the original list is using List.Sort
:
People.Sort((p1,p2) => p1.LastName.CompareTo(p2.LastName));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With