I have a list of passengers(object) where it has a differents properties..
passenger.name passenger.age passenger.surname
And I want to sort this list by age criterion, how can i do this?
I know in a list of integer/string List.Sort() works, but if is an object list, i dont know if its possible to sort by the value of a object property!
Thanks.
Using the OrderBy() Method in LINQ The most common way of sorting lists is by using the OrderBy() LINQ method to create a new, sorted copy of the original list. This creates a new list with the elements sorted by using a key. This key should be a property of the object.
Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
To sort by a property in the object, you have to specify a comparer or a method to get that property.
Using the List.Sort
method:
theList.Sort(Function(x, y) x.age.CompareTo(y.age))
Using the OrderBy
extension method:
theList = theList.OrderBy(Function(x) x.age).ToList()
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