2015-09-04 105 views
1

如何在運行時爲以下代碼動態指定組密鑰?Linq Dynamic Group Key

Dim query = From c In data 
      Group By groupKey = c.City 
      Into groupName = Group 

For Each item In query 
    Console.WriteLine(item.groupKey) 

    For Each row In item.groupName 
     Console.WriteLine(Convert.ToString(row.CompanyName) & ": " & Convert.ToString(row.Contact_Name)) 
    Next 
Next 

回答

0

在分配到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)