Phil Murray
Phil Murray

Reputation: 6554

Linq query on IList<T> string member

I have the below model which I am loading into an IList collection and running a Linq query against. The problem I have is that the Linq query return the OPCServer member as an IEnumerable(of Char). Is there a reason why this is not returning the underlying string?

If I iterate of the collection with a For Each then it returns the string as expected.

Do I have to manually convert it back as show in the working code section?

Model

Friend Class OpcDataTags

    Public Property Host As String
    Public Property HostLive As Boolean
    Public Property OpcServer As String
    Public Property OpcChannel As String
    Public Property PlcDns As String
    Public Property PlcIP As String
    Public Property Zone As String
    Public Property DataBlock As String
    Public Property StartByte As Int16
    Public Property ByteSize As Int16
    Public Property DataType As String
    Public Property Subscribed As Boolean
    Public Property Description As String
    Public Property ArraySize As Nullable(Of Int32)
    Public Property Abbreviation As String
    Public Property PlcID As Int32

End Class

Collection

Friend Property OpcTags As IList(Of OpcDataTags)

LinqQuery

Dim server = From o In OpcTags.First.OpcServer

Working code

Dim result = From o In OpcTags.First.OpcServer
Dim server As String = New String(result.ToArray)

Upvotes: 0

Views: 716

Answers (1)

Eduard Dumitru
Eduard Dumitru

Reputation: 3252

What you actually wanted to achieve was this:

' From LINQ's point of view, OpcTags is an IEnumerable< OpcDataTags >
Dim serverQuery = From o In OpcTags Select o.OpcServer
' And now you've narrowed it down to an IEnumerable< String >

Dim firstOne = serverQuery.First
' And now you're selecting the first String from that enumeration of strings

Please also note that this can throw an exception should the enumeration yield no strings.

If that condition is possible and also the effect would be unpleasant you could use FirstOrDefault instead

Dim firstOne_OrNothingIfNone = serverQuery.FirstOrDefault

The String class implements IEnumerable< Char > and you were actually forcing it to look like a source of more values (thus implicitly casting it to the best IEnumerable match, which was IEnumerable< Char >)

Upvotes: 3

Related Questions