3

I have an application in Visual Basic.Net and need to find all elements within an array which meet a certain condition.

Dim result As my_obj() = Array.FindAll(lstData, HasToBeSent)

Where the function HasToBeSent is defined like this:

Private Function HasToBeSent(ByVal cta As my_obj) As Boolean
    Return cta.IsSent
End Function

However this doesn't compile, it says I haven't specified an argument for the parameter cta in Private Function HasToBeSent(ByVal cta As my_obj) As Boolean

I am using Visual Studio 2005, therefore I have VB.Net 8.0. I am guessing the suggested answer is for higher versions of VB.Net. Because when I replace the previous code with

Dim result As my_obj() = Array.FindAll(lstData, Function(cta) HasToBeSent(cta))

It says: "expression expected"

How can I solve this?

2
  • 4
    Why is this tagged with both vb6 and vb.net tags? Commented May 17, 2013 at 21:14
  • 1
    @soph: That is not VB6 code. It is vb.net. As such, I've removed the incorrect tag. Commented May 17, 2013 at 22:22

1 Answer 1

4

Keep your HasToBeSent definition but add the Shared keyword to it to make it static (actually this is probably optional, but since this code doesn't rely on anything else in your class, it's probably a good design decision anyway).

Private Shared Function HasToBeSent(ByVal cta As my_obj) As Boolean
    Return cta.IsSent
End Function

And then in Array.FindAll(), give it the "address of" your function:

Array.FindAll(lstData, AddressOf HasToBeSent)

If you upgrade to a newer version of VB, then you can inline a delegate:

Array.FindAll(lstData, Function(cta) cta.IsSent)

To keep the HasToBeSent function, you can simply call that instead:

Array.FindAll(lstData, Function(cta) HasToBeSent(cta))
Sign up to request clarification or add additional context in comments.

9 Comments

I just edited my question explaining why your solution doesn't work for me. Could you take a look at it?
@Soph: I updated my answer. Hopefully we got it this time! :)
If LINQ is supported, I would go with this: lstData.Where(Function(cta) cta.IsSent).ToArray, just find it more intuitive.
@Neolisk: I would agree, but LINQ support didn't show up until VB.NET/VS 2008 :/
@Soph: My bad. It's been a while since I've used 2005. I updated again -- read it carefully, the change is very subtle.
|

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.