我有一个VB.NET应用程序,并希望在多个列上执行Group By。
班级结构:
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查询时出错了。
答案 0 :(得分:21)
问题是匿名类型中只有Key
属性用于VB中的相等和散列。 ( C#匿名类型中的所有属性都是有效的关键属性。)因此,您只需将查询更改为:
Dim oResult = PersonList _
.GroupBy(Function(v) New With { Key v.City, Key v.Country}) _
.Where(Function(grp) grp.Count > 1).ToList()
有关详细信息,请参阅anonymous types in VB的文档。
答案 1 :(得分:3)
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