我在这个问题上花了很多时间。我可以做简单的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应该分组。
提前谢谢。
发布于 2011-06-11 00:06:49
不是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;
}
}发布于 2012-03-06 16:03:14
使用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)
} 发布于 2011-06-14 14:28:03
谢谢!但我注意到我还需要编写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)}https://stackoverflow.com/questions/6308851
复制相似问题