vb.net 具有多个参数的 LINQ 分组依据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14660240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ Group By with multiple parameters
提问by Jignesh Thakker
I have a VB.NET application and want to do Group By on multiple columns.
我有一个 VB.NET 应用程序,想在多列上进行分组。
Class Structure:
班级结构:
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()
I have multiple person records which contains same city name & country name. But above query returns me zero items. if I am using only one column City or Country then it's working fine.
我有多个人记录,其中包含相同的城市名称和国家/地区名称。但上面的查询返回零项。如果我只使用一列城市或国家,那么它工作正常。
Dim oResult = PersonList _
.GroupBy(Function(v) v.City) _
.Where(Function(grp) grp.Count > 1).ToList()
Anyone point me where I am wrong with Group By LINQ query with multiple parameters.
任何人都可以指出我对带有多个参数的 Group By LINQ 查询的错误之处。
回答by Jon Skeet
The problem is that only Key
properties in anonymous types are used in equality and hashing in VB. (Allproperties in C# anonymous types are effectively key properties.) So you just need to change your query to:
问题是只有Key
匿名类型的属性才能用于 VB 中的相等和散列。(C# 匿名类型中的所有属性实际上都是关键属性。)因此,您只需将查询更改为:
Dim oResult = PersonList _
.GroupBy(Function(v) New With { Key v.City, Key v.Country}) _
.Where(Function(grp) grp.Count > 1).ToList()
See the documentation for anonymous types in VBfor more details.
有关更多详细信息,请参阅VB 中匿名类型的文档。
回答by Mohammad Karimi
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
Or
或者
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