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?

3
  • You don't need to sort if you want to find the greatest number. Commented Sep 28, 2016 at 12:04
  • In what other way could I do this? Commented Sep 28, 2016 at 12:14
  • 1
    there are some example here, here and here. Commented Sep 28, 2016 at 12:24

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

5 Comments

based on this, you can use Dim top5Bananas = btree.OrderByDescending(function(b) b.Bananas).Take(5)
@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).
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 :)
Thanks for the help, this solved my problem! If I understand you correctly, I should always use List instead of Arraylist?
Yes. There's no reason to use ArrayList anymore

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.