2013-02-02 77 views
10

我有一個VB.NET應用程序,並希望在多個列做分組。LINQ集團由多個參數

階層結構:

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

任何人指出我在哪裏我錯了羣由LINQ查詢與多個參數。

回答

18

問題是隻有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

謝謝!它像一個魅力。 –

2
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