0

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 Sep 28 '16 at 12:04
  • In what other way could I do this? – Jan met de korte Achternaam Sep 28 '16 at 12:14
  • 1
    there are some example [here](http://stackoverflow.com/questions/4956593/optimal-algorithm-for-returning-top-k-values-from-an-array-of-length-n), [here](http://stackoverflow.com/questions/32395648/largest-5-in-array-of-10-numbers-without-sorting) and [here](http://stackoverflow.com/questions/4084495/find-top-n-elements-in-an-array). – the_lotus Sep 28 '16 at 12:24

1 Answers1

2

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()
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • based on this, you can use `Dim top5Bananas = btree.OrderByDescending(function(b) b.Bananas).Take(5)` – Keith Mifsud Sep 28 '16 at 12:00
  • @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). – Tim Schmelter Sep 28 '16 at 12:19
  • 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 :) – Keith Mifsud Sep 28 '16 at 12:31
  • Thanks for the help, this solved my problem! If I understand you correctly, I should always use List instead of Arraylist? – Jan met de korte Achternaam Sep 28 '16 at 16:34
  • Yes. There's no reason to use ArrayList anymore – Tim Schmelter Sep 28 '16 at 17:45