Linq动态组密钥

时间:2015-09-04 18:52:26

标签: .net vb.net linq

如何在运行时为以下代码动态指定组键?

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

1 个答案:

答案 0 :(得分: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)