Summarise arbitrary data with LINQ
In C#, given a class definition like this:
public class SomeObject
{
public String A { get; set; }
public String B { get; set; }
public Stri开发者_StackOverflow中文版ng 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.
var groups = objects.GroupBy(o => new {
A = GroupByA ? o.A : null,
B = GroupByB ? o.B : null,
C = GroupByC ? o.C : null
});
foreach (var g in groups)
{
Console.WriteLine("There are {0} objects with A = {1} and B = {2} and C = {3}",
g.Count(),
g.Key.A,
g.Key.B,
g.Key.C);
}
Some more sophisticated formatting can be done to handle C=null
key part.
You can group by an anonymous type with two properties:
objects.GroupBy(o => new { o.A, o.B });
精彩评论