c# - Count all elements in a tree that meet a condition using LINQ -


this question has answer here:

i have list of person objects. each person has list of persons property. here's class.

 public class person  {             public list<person> team { get; set; }      public string status {get; set;}  } 

so each person has parent, list of children, , status.

i need count number of times status equals "x" or "y" in given person's tree. told use .aggregate() function, i'm not sure how that.

for example, if person had list of 3 people status "x" , each of people had lists of 3 people, 2 status "x" , 1 status "z", 12 people total , count of "x" 9.

you recursively "flatten" tree, example (using post-fix iterator):

public class person {     public list<person> team { get; set; }     public string status { get; set; }      public ienumerable<person> flatten()     {         yield return this;          foreach (var person in team)             foreach (var child in person.flatten())                 yield return child;     }  } 

and then, using "root" person, this:

var count = person.flatten().count(p => p.status == "x" || p.status == "y"); 

if had collection of people, combine selectmany flatten.

people.selectmany(p => p.flatten()).count(...) 

Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -