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?
-
You don't need to sort if you want to find the greatest number.the_lotus– the_lotus2016-09-28 12:04:06 +00:00Commented Sep 28, 2016 at 12:04
-
In what other way could I do this?Jan met de korte Achternaam– Jan met de korte Achternaam2016-09-28 12:14:35 +00:00Commented Sep 28, 2016 at 12:14
-
1there are some example here, here and here.the_lotus– the_lotus2016-09-28 12:24:42 +00:00Commented Sep 28, 2016 at 12:24
Add a comment
|
1 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()
5 Comments
Keith Mifsud
based on this, you can use
Dim top5Bananas = btree.OrderByDescending(function(b) b.Bananas).Take(5)Tim Schmelter
@KeithMifsud: yes, that's method syntax, doesn't make a real difference. I often prefer query syntax in VB.NET because it's more powerful (than in C#, f.e.
Take is supported) and more readable (because of the ugly Function-keyword).Keith Mifsud
yes, they are both doing the same thing, I just posted it to let the OP have both choices presented to him. Personally, with complex queries, method syntax helps me more :)
Jan met de korte Achternaam
Thanks for the help, this solved my problem! If I understand you correctly, I should always use List instead of Arraylist?
Tim Schmelter
Yes. There's no reason to use ArrayList anymore