1

I have a list of objects of type Pump, each one of them holding a reference to an object of type Valve, exposed through its property Valve.

Public Class Pump

    Private _valve As Valve 'may be Nothing

    Public ReadOnly Property Valve() As Valve
        Get
            Return _valve 
        End Get
    End Property
End Class

However, the valve can exist or just be Nothing.

It there an easy way to select all the valves and put them in a list?

I tried this:

_pumps.Select(Of Valve)(Function(p As Pump) p.Valve).ToList

But I get a list with some of the objects being Nothing, since there was no valve asigned to the correspondent pump.

I have finally done this:

Dim valves As New List(Of Valve)
    For Each p As PumpIn _pumps
        If p.Valve IsNot Nothing Then
            valves.Add(p.Valve)
        End If
    Next

But I was wondering if there is a more compact way of doing it:

Thanks!

1 Answer 1

3

I think the following will help:

_pumps.Where(Function(p) p.Valve IsNot Nothing).Select(Of Valve)(Function(p As Pump) p.Valve).ToList
Sign up to request clarification or add additional context in comments.

4 Comments

The Where clause should check for null valve not null pump.
@meta-knight You were right and i changed it, though i think a downvote was a bit too harsh in this case. ;-)
Yeah, you were on the right track and now it's fixed. Upvoted instead :-) One more thing to note, you can just write .Select(Function(p) p.Valve) without the (Of Valve) and As Pump parts which are superfluous.
@meta-knight I know and this is how i would write it, but i wanted to keep the changes to the minimum.

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.