在分配到groupKey
時,您可以使用某個功能。例如,請考慮以下類和枚舉。
Class Company
Public Property City() As String
Public Property State() As String
Public Property CompanyName() As String
Public Property Contact_Name As String
End Class
Class CompanyGroup
Public Property Companies() As IEnumerable(Of Company)
Public Property GroupKey() As String
End Class
和下面的函數來處理查詢:
Function GetGroupKey(type As GroupType, c As Company) As String
If type = GroupType.City Then
Return c.City
ElseIf type = GroupType.State Then
Return c.State
Else
Return c.CompanyName
End If
End Function
Function GetQuery(type As GroupType, data As List(Of Company)) As IEnumerable(Of CompanyGroup)
Return From c In data
Group By groupKey = GetGroupKey(type, c)
Into group = Group
Select New CompanyGroup With {.Companies = group, .GroupKey = groupKey}
End Function
現在你可以讓這些調用:
'Will contain three groups for Miami, Jacksonville, and Atlanta
Dim cityGroups As IEnumerable(Of CompanyGroup) = GetQuery(GroupType.City, data)
'Will contain two groups for FL and GA
Dim stateGroups As IEnumerable(Of CompanyGroup) = GetQuery(GroupType.State, data)