LINQ查询InvalidCastException [英] LINQ Query InvalidCastException
本文介绍了LINQ查询InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以告诉我为什么我的LINQ查询功能失败了吗?
Can someone tell me why my LINQ query function is failing?
Public Function PC_Archived(ByVal strPC As String, _
ByVal dtName As DataTable) _
As Long
'Purpose: Check as see if this PC is registered
' for archiving
'Parameters: strPC - PC's Name we are looking for
' dtName - The DataTable where the PC
' names are stored
'Returns:
Dim lngPCID As Long
Debug.Print("Table: " & dtName.TableName.ToString & vbCrLf & _
vbTab & "Numder of Rows: " & dtName.Rows.Count.ToString)
Dim Query = _
From PC In dtName.AsEnumerable() _
Where PC.Field(Of String)("PC_Name") = strPC _
Select New With _
{ _
.PCID = PC.Field(Of Long)("PCID"), _
.PCName = PC.Field(Of String)("PC_Name") _
}
For Each PC In Query
Debug.Print("PCID: " & PC.PCID)
Debug.Print("PC Name: " & PC.PCName)
lngPCID = PC.PCID
Next
Return lngPCID
End Function
当它执行For Each语句时,我得到InvalidCastException is Unhandled。错误。
谢谢,
When it executes the For Each statement I get "InvalidCastException was Unhandled." error.
Thanks,
推荐答案
此查询返回一个匿名对象 -
This query returns an anonymous object -
Dim Query = _
From PC In dtName.AsEnumerable() _
Where PC.Field(Of String)("PC_Name") = strPC _
Select New With _
{ _
.PCID = PC.Field(Of Long)("PCID"), _
.PCName = PC.Field(Of String)("PC_Name") _
}
因此你不能直接将它转换为 PC
in For Each PC In Query
Thus you cannot directly convert it to PC
in For Each PC In Query
For Each PC In Query
Debug.Print("PCID: " & PC.PCID)
Debug.Print("PC Name: " & PC.PCName)
lngPCID = PC.PCID
Next
想出来。
Figured it out.
Dim Query = (From PC In dtName _
Where PC.Field(Of String)("PC_Name") = strPC _
Select PC.Field(Of Int32)("PCID")).FirstOrDefault()
这篇关于LINQ查询InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文