使用 LINQ 汇总任意数据
在 C# 中,给定如下所示的类定义:
public class SomeObject
{
public String A { get; set; }
public String B { get; set; }
public String C { get; set; }
}
并给定 SomeObject
的集合,我希望我的应用程序能够计算按 A、B 和 C 的任意组合分组的 SomeObject 的数量。我可以使用 LINQ 查询来执行此操作,或者如果没有,我可以编写一些算法吗?
鉴于此:
List<SomeObject> objects;
bool GroupByA;
bool GroupByB;
bool GroupByC;
如果 GroupByA 为 true,我想按 SomeObject.A 对对象进行分组;如果 GroupByB 为 true,则按 B 对对象进行分组;如果 GroupByC 为 true,则按 C 对对象进行分组。我知道我可以通过 objects.GroupBy(o => oA);
执行其中任何一个,但是接下来我该如何按 B 和/或进行分组C?
我希望这是有道理的。我希望得到的是这样的:
There are 10 objects with A = "Smith" and B = "London"
There are 20 objects with A = "Jones" and B = "London"
There are 44 objects with A = "Jones" and B = "Inverness"
等等等等。提前谢谢你。
In C#, given a class definition like this:
public class SomeObject
{
public String A { get; set; }
public String B { get; set; }
public String C { get; set; }
}
and given a collection of SomeObject
s, I want my application to be able to count the number of SomeObjects grouped by any combination of A, B and C. Is there a LINQ query I can use to do this, or if not, some algorithm I can write?
Given this:
List<SomeObject> objects;
bool GroupByA;
bool GroupByB;
bool GroupByC;
I want to group objects
by SomeObject.A if GroupByA is true, by B if GroupByB is true, and by C if GroupByC is true. I understand that I can do any one of these by objects.GroupBy(o => o.A);
but then how do I then go and group by B and/or C?
I hope that makes sense. What I'm hoping to get out is something like this:
There are 10 objects with A = "Smith" and B = "London"
There are 20 objects with A = "Jones" and B = "London"
There are 44 objects with A = "Jones" and B = "Inverness"
etc. etc. Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以进行一些更复杂的格式化来处理
C=null
关键部分。Some more sophisticated formatting can be done to handle
C=null
key part.您可以按具有两个属性的匿名类型进行分组:
You can group by an anonymous type with two properties: