如果我使用
Dim kun = From cus In customers
Group By cus.Country
Into Group
Northwind上的(我得到IEnumerable.Collections.Generic.Ienumerable(of <anonymous Type>)
)我可以执行以下循环:
For Each kdGroup In kun
ListBox1.Items.Add(kdGroup.Country)
For Each kd In kdGroup.Group
ListBox1.Items.Add(" " & kd.CompanyName)
Next
Next
我可以访问该成员(.Country
和.CompanyName
)。
但是如果我使用Extension Method(或Dot Notation)语法:
Dim kun = customers.GroupBy(Function(k) k.Country)
(我得到一个IEnumerable(Of System.Linq.IGrouping(String,... CustomerRow)))我无法执行上面显示的循环,因为我现在无法访问成员。这是一本书的例子,所以我认为它应该有效。任何人都可以向我解释一下,为什么DotNotation在这里不起作用以及这个片段有什么问题?
答案 0 :(得分:0)
以下是展示如何访问Country
和CountryName
使用GroupBy
Sub Main
Dim empList As New List(Of Employee)()
empList.Add(New Employee() With _
{.ID = 1, .FName = "John", .Age = 21, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 2, .FName = "Mary", .Age = 25, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 3, .FName = "Amber", .Age = 23, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 4, .FName = "Kathy", .Age = 25, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 5, .FName = "Lena", .Age = 27, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 6, .FName = "Bill", .Age = 28, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 7, .FName = "Celina", .Age = 27, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 8, .FName = "John", .Age = 28, .Sex = "M"c})
Dim query = empList.GroupBy(Function(x) New with{.Age= x.Age})
For Each employee In query
Console.WriteLine(employee.Key.Age)
For Each kd In employee
Console.WriteLine(" " & kd.FName)
Next
Next employee
End Sub
Public Class Employee
Private privateID As Integer
Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateFName As String
Public Property FName() As String
Get
Return privateFName
End Get
Set(ByVal value As String)
privateFName = value
End Set
End Property
Private privateAge As Integer
Public Property Age() As Integer
Get
Return privateAge
End Get
Set(ByVal value As Integer)
privateAge = value
End Set
End Property
Private privateSex As Char
Public Property Sex() As Char
Get
Return privateSex
End Get
Set(ByVal value As Char)
privateSex = value
End Set
End Property
End Class
结果:
21
John
25
Mary
23
Amber
25
Kathy
27
Lena
28
Bill
27
Celina
28
John
答案 1 :(得分:0)
你仍然可以让你的循环工作:
For Each kdGroup In kun
ListBox1.Items.Add(kdGroup.Key)
For Each kd In kdGroup
ListBox1.Items.Add(" " & kd.CompanyName)
Next
Next