Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List of Object in VB.NET

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.

like image 352
bombai Avatar asked Jul 31 '12 08:07

bombai


People also ask

How do I sort a list of objects in VB net?

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.

How to Sort a List in. net?

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.


1 Answers

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() 
like image 183
Guffa Avatar answered Oct 15 '22 01:10

Guffa