17

私は 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()

同じ都市名と国名を含む個人レコードが複数あります。しかし、上記のクエリではアイテムが返されません。City または Country の列を 1 つだけ使用している場合は、正常に機能しています。

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

複数のパラメーターを使用した Group By LINQ クエリのどこが間違っているか、誰でも指摘してくれます。

4

2 に答える 2

30

問題はKey、匿名型のプロパティのみが VB の等価性とハッシュで使用されることです。( 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 に答える