我花了很多时间在这个问题上.我可以做简单的Group By LINQ查询(在一个属性上),但是对于多个字段我有点卡住了
这是一个LINQPad我想要做的样品:
这是一个LINQPad我想要做的样品:
dim lFinal={new with {.Year=2010,.Month=6,.Value1=0,.Value2=0},new with {.Year=2010,.Value1=2,.Value2=1},.Month=7,.Value1=3,.Value2=4},.Month=8,new with {.Year=2011,.Month=1,.Value2=2},.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应该组合.
提前致谢.
不是100%确定但是组可能使用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; } }