Jan met de korte Achternaam Jan met de korte Achternaam - 2 months ago 7
Vb.net Question

Fastest way to sort arraylist of objects by value of a property

Just as an example, I have a bananaTreeArray which is filled with 1000 BananaTree objects. Each of those BananaTree objects has a public property called Bananas. What is the fastest/easiest way for me to find the 5 BananaTree's with the most banana's?

Answer

Don't use ArrayList but a generic and strongly typed List(Of T), in this case a List(Of BananaTree). Then it's simple with LINQ:

Dim top5Bananas = From btree In bananaTreeArray
                  Order by btree.Bananas Descending
                  Take 5

If it's really an ArrayList you have to cast every object:

Dim top5Bananas = From btree In bananaTreeArray.Cast(of BananaTree)()
                  Order by btree.Bananas Descending
                  Take 5

You can either loop this query with a For Each or create a list/array, f.e.:

Dim top5BananaList = top5Bananas.ToList()