VB.Net 中具有多个属性的 LINQ 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 应该分组。
提前致谢。
I spent a lot of time on this problem. I am able to do simple Group By LINQ queries (on one property) but for multiple fields I'm a little stuck...
Here is a LINQPad sample of what I want to do :
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()
The lFinal list has 6 items, I want the lFinal2 to have 4 items : 2010-6 and 2011-1 should group.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
Key
关键字使匿名类型中的属性不可变,然后将它们用于比较Make the properties in the anonymous type immutable using the
Key
keyword and then they will be used for comparisons谢谢 !
但我注意到我还需要编写 GetHashCode 函数才能使其正常工作。我提供最终类 + LINQ GroupBy 的 VB.Net 翻译:
类:
以及 LINQ 查询:
Thanks !
But I noticed I needed to also write the GetHashCode function to make it works. I provide the VB.Net translation of the final class + LINQ GroupBy :
Class :
And the LINQ query :
不是 100% 确定,但 group by 可能使用 Equals() 和/或 GetHashCode 实现,因此当您执行隐式创建时:
隐式对象不知道检查年份和月份(仅仅因为它具有属性不意味着它在与其他对象进行比较时检查它们)。
所以你可能需要做更多类似这样的事情:
Not 100% sure but group by probably uses the Equals() and/or GetHashCode implementation, so when you do the implicit creation:
the implicit object doesn't know to check both year and month (just because it has the properties doesn't mean it checks them when comparing to other objects).
So you'll probably need to do something more like this: