我有以下模型,我将其加载到IList集合并运行Linq查询。我遇到的问题是Linq查询将OPCServer成员作为IEnumerable(Char)返回。有没有理由不返回基础字符串?
如果我用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)
LinqQuery
Dim server = From o In OpcTags.First.OpcServer
工作代码
Dim result = From o In OpcTags.First.OpcServer
Dim server As String = New String(result.ToArray)
答案 0 :(得分: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 >
)