我有一個Linq組通過查詢的工作。這裏的查詢:VB.Net Linq組InvalidCastException由
Dim query = From fb As Feedback In lst Where fb.Seller.login_name.ToLower = UserName.ToLower
Order By fb.transaction_id Descending, fb.creation Descending _
Group fb By fb.transaction_id _
Into Group
我不喜歡用匿名類型工作,所以我想delare結果和我打的InvalidCastException的。
這裏的類型信息:
Debug.Print(query.GetType.ToString)
返回:
System.Linq.GroupedEnumerable`4[Feedback,System.Nullable`1[System.Int32],Feedback,VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]
和內型:
Debug.Print(item.GetType.ToString)
返回:
VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]
所以,有了這些信息,這裏的二手聲明:
Dim query As IEnumerable(Of IGrouping(Of Int32?, IEnumerable(Of Feedback)))
這裏的錯誤返回:
Unable to cast object of type 'System.Linq.GroupedEnumerable`4[Feedback,System.Nullable`1[System.Int32],Feedback,VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]' to type 'System.Collections.Generic.IEnumerable`1[System.Linq.IGrouping`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]'.
醜陋的解決方案是定義一個對象,並通過結果步驟如下:
Class FeedbackDataItem
Sub New(ByVal transaction_id As Integer)
_transaction_id = transaction_id
_feedbacks = New Feedbacks(Of Feedback)
End Sub
Private _transaction_id As Integer
Public Property transaction_id() As Integer
Get
Return _transaction_id
End Get
Set(ByVal value As Integer)
_transaction_id = value
End Set
End Property
Private _feedbacks As Feedbacks(Of Feedback)
Public Property Feedbacks() As Feedbacks(Of Feedback)
Get
Return _feedbacks
End Get
Set(ByVal value As Feedbacks(Of Feedback))
_feedbacks = value
End Set
End Property
End Class
並加載了集合:
Dim FeedbackData As New List(Of FeedbackDataItem)
For Each item In query
Dim fbi As New FeedbackDataItem(item.transaction_id)
fbi.Feedbacks.AddRange(item.Group)
FeedbackData.Add(fbi)
Next
我很難理解爲什麼我得到這個錯誤。只是定義結果並反思它們而不是人爲處理數據會更好。我錯過了什麼嗎?
這正是我想要的:)現在刪除我的答案... – 2010-12-12 09:04:03
這很好用 - 謝謝! – Graeme 2010-12-12 09:09:46