LINQ Group在VB.Net中具有多个属性

时间:2011-06-10 15:49:15

标签: vb.net linq list group-by

我花了很多时间来解决这个问题。我可以做一个简单的Group By LINQ查询(在一个属性上)但是对于多个字段我有点卡住... 这是我想要做的LINQPad示例:

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应该分组。

提前致谢。

3 个答案:

答案 0 :(得分:19)

使用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)
    } 

答案 1 :(得分: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)}

答案 2 :(得分: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;
    }
}