0

我有以下模型,我将其加载到 IList 集合中并针对其运行 Linq 查询。我遇到的问题是 Linq 查询将 OPCServer 成员作为 IEnumerable(of Char) 返回。这是否有理由不返回基础字符串?

如果我用 a 迭代集合,For Each那么它会按预期返回字符串。

我是否必须手动将其转换回工作代码部分中的显示?

模型

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

收藏

Friend Property OpcTags As IList(Of OpcDataTags)

查询

Dim server = From o In OpcTags.First.OpcServer

工作代码

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

1 回答 1

3

你真正想要实现的是:

' 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

另请注意,如果枚举不产生字符串,这可能会引发异常。

如果这种情况是可能的,而且效果也会令人不快,您可以FirstOrDefault改用

Dim firstOne_OrNothingIfNone = serverQuery.FirstOrDefault

String 类实现IEnumerable< Char >了,您实际上是在强迫它看起来像更多值的来源(因此隐式将其强制转换为最佳IEnumerable匹配,即IEnumerable< Char >

于 2013-02-28T11:04:00.160 回答