2011-06-10 68 views
9

我在這個問題上花了很多時間。我能夠做簡單的集團通過LINQ查詢(在一個屬性),但多個字段我有點卡住... 這裏是什麼,我想做一個LINQPad樣本:LINQ Group by with VB.Net中的多個屬性

dim lFinal={new with {.Year=2010, .Month=6, .Value1=0, .Value2=0}, 
      new with {.Year=2010, .Month=6, .Value1=2, .Value2=1}, 
      new with {.Year=2010, .Month=7, .Value1=3, .Value2=4}, 
      new with {.Year=2010, .Month=8, .Value1=0, .Value2=1}, 
      new with {.Year=2011, .Month=1, .Value1=2, .Value2=2}, 
      new with {.Year=2011, .Month=1, .Value1=0, .Value2=0}} 

Dim lFinal2 = From el In lFinal 
       Group el By Key = new with {el.Year,el.Month} 
       Into Group 
       Select New With {.Year = Key.Year, .Month=Key.Month, .Value1 = Group.Sum(Function(x) x.Value1), .Value2 = Group.Sum(Function(x) x.Value2)} 

lFinal.Dump() 
lFinal2.Dump() 

的lFinal目錄中有6個項目,我想讓lFinal2有4個項目:2010-6和2011-1應該分組。

在此先感謝。

+0

我也ha d來實現GetHashCode()以使其工作。 – Maher 2013-01-02 12:45:39

回答

4

不是100%肯定,但GROUP BY可能使用equals()和/或GetHashCode的實現,所以當你做隱式創建:

= Group el By Key = new with {el.Year,el.Month} 

隱含對象不知道這兩個年度檢查和月(僅僅因爲它具有屬性並不意味着它在與其他對象比較時檢查它們)。

所以你可能需要做更多的東西是這樣的:

= Group el By Key = new CustomKey() { Year = el.Year, Month = el.Month }; 

public class CustomKey{ 
    int Year { get; set; } 
    int Month { get; set; } 

    public override bool Equals(obj A) { 
     var key (CustomKey)A; 
     return key.Year == this.Year && key.Month == this.Month; 
    } 
} 
+0

+1。雖然OP的語法在LINQ-to-SQL中可以正常工作,但在LINQ-to-Objects上使用時會產生當前輸出。 – 2011-06-10 16:33:13

+1

+0雖然這是正確的,但「Key」關鍵字是正確的答案。 – 2012-03-06 09:09:41

5

謝謝! 但我注意到我還需要編寫GetHashCode函數來使其工作。我公司提供的最後一節課+ LINQ的GroupBy的VB.Net翻譯:

類:

Public Class YearMonth 
    Implements IEquatable(Of YearMonth) 

    Public Property Year As Integer 
    Public Property Month As Integer 

    Public Function Equals1(other As YearMonth) As Boolean Implements System.IEquatable(Of YearMonth).Equals 
     Return other.Year = Me.Year And other.Month = Me.Month 
    End Function 

    Public Overrides Function GetHashCode() As Integer 
     Return Me.Year * 1000 + Me.Month * 100 
    End Function 
End Class 

而且LINQ查詢:

Dim lFinal2 = From el In lFinal 
       Group el By Key = New YearMonth With {.Year = el.Year, .Month = el.Month} 
       Into Group 
       Select New ItemsByDates With {.Year = Key.Year, 
              .Month = Key.Month, 
              .Value1 = Group.Sum(Function(x) x.Value1), 
              .Value2 = Group.Sum(Function(x) x.Value2)} 
+1

+0雖然這是正確的,但「Key」關鍵字是正確的答案。 – 2012-03-06 09:10:20

18

請在匿名類型的屬性來永恆不變Key關鍵字然後他們將用於比較

Dim lFinal2 = From el In lFinal    
    Group el By Key = new with {key el.Year, key el.Month} 
    Into Group 
    Select New With { 
      .Year = Key.Year, 
      .Month = Key.Month, 
      .Value1 = Group.Sum(Function(x) x.Value1), 
      .Value2 = Group.Sum(Function(x) x.Value2) 
    }