17

我有一个 VB.NET 应用程序并希望在多个列上进行分组。

班级结构:

Public Class Person
   Public Property Name as String
   Public Property City as String
   Public Property Country as String
End Class

Dim oResult = PersonList _
                .GroupBy(Function(v) New With {v.City, v.Country}) _
               .Where(Function(grp) grp.Count > 1).ToList()

我有多个包含相同城市名称和国家名称的人员记录。但上面的查询返回我零个项目。如果我只使用一列城市或国家,那么它工作正常。

Dim oResult = PersonList _
                .GroupBy(Function(v) v.City) _
               .Where(Function(grp) grp.Count > 1).ToList()

任何人都指出我对具有多个参数的 Group By LINQ 查询的错误之处。

4

2 回答 2

30

问题是在 VB 中,只有Key匿名类型的属性用于相等和散列。( C# 匿名类型中的所有属性实际上都是关键属性。)因此您只需将查询更改为:

Dim oResult = PersonList _
                .GroupBy(Function(v) New With { Key v.City, Key v.Country}) _
                .Where(Function(grp) grp.Count > 1).ToList()

有关详细信息,请参阅VB 中匿名类型的文档。

于 2013-02-02T08:55:37.047 回答
4
Dim q1 = (From p In Repository.Table
                            Group p By p.CreatedDate.Year, p.CreatedDate.Month Into Group
                            Select New With {.Year = Year, .Month = Month, .Count = Group.Count()}).ToList

或者

Dim q2 = (From p In Repository.Table
                            Group p By key = New With {.Year = p.CreatedDate.Year, .Month = p.CreatedDate.Month} Into Group
                            Select New With {.Year = key.Year, .Month = key.Month, .Count = Group.Count()}).ToList
于 2015-01-20T02:56:39.873 回答