尝试做一些我确信应该很简单的事情,但是要努力学习linq和VB。我有下面的内容,我正在将一个集合分组,然后想要访问我的组的属性。我遇到的问题是匿名输入。由于选项严格,我必须给出一个显式类型,但我无法确定类型应该是什么。下面没有编译,因为t.HeadAccountKey不是一个值(因为t有一种对象)。所以要么我需要做一些演员,要么我的linq选择器是错的,
public class TempObject
public HeadKey as string
Public SubKey as string
Public SomeValue as decimal
end class
public class GroupTest
public sub RunTest
dim collection new List(of TempObject) = GetTestCollection()
Dim groupedValues As IEnumerable = From n In collection _
Group By key = n.HeadKey Into Group Select HeadKeyValue = key, SubValues = Group
for each t as object in groupedValues
debug.print(t.HeadKeyValue)
next
End sub
private function GetTestCollection() as List(of TempObject)
dim result as new list(of tempobject)
Dim x As New tempObject
x.HeadAccountNumber = "A"
x.SubAccountNumber = "B"
x.Value = 500
result.Add(x)
x = New tempObject
x.HeadAccountNumber = "A"
x.SubAccountNumber = "C"
x.Value = 600
result.Add(x)
x = New tempObject
x.HeadAccountNumber = "B"
x.SubAccountNumber = "D"
x.Value = 100
result.add(x)
return result
end function
End class
答案 0 :(得分:1)
您不需要指定类型,至少使用Option Infer on
(可推荐,不要与Option Strict
混淆)。
以下作品:
Dim collection = GetTestCollection()
Dim groupedValues = From n In collection
Group n By n.HeadKey Into Group
For Each t In groupedValues
Dim hk = t.HeadKey
Dim group = t.Group
Next