tags:

views:

44

answers:

5

Hi!

I need to do a foreach to find all my subordinates and that includes to find all of the subordinates of my subordinates and so on...

I was trying to accomplish but I couldn't pass to find the 2nd level of subordinates...

Thanks!!

+1  A: 

Did you try to use recursion?

Prutswonder
A: 

Something like the following?

object RecursiveCall(Collection collection, object itemToFind)
{
    foreach(var item in collection)
    {
        if(item == itemToFind)
        {
             return item;
        }
        else
        {
             RecursiveCall(item, itemToFind);
        }
    }
}
Datoon
He isn't looking for a subordinate, he's trying to collapse all subordinates.
Will
+3  A: 
private IEnumerable<Employee> RecursiveGet(Employee durr)
{
  foreach(var sub in durr.Subordinates)
  {
    yield return sub;
    foreach(var recurse in RecursiveGet(sub))
      yield return recurse;
  }
}
Will
I might change this to be an extension rather than a method. Also, this would be a lot of fun if C# allowed yields in lambda's/anonymous methods.
itchi
A: 

Go for an implementation of recursive technique for this.

Kangkan
A: 

PSUDO:

  private List<Subordinate> GetSubordinates(Subordinate you){
        List<Subordinate> subs = new List<Subordinate>();
        if(!you.HasSubordinates){
              return subs;
         }

         foreach(Subordinate s in you.Subordinates){
            subs.AddRange(GetSubordinates(s));
        }
  }
Nix
That is so wrong on so many levels.
Will
So many levels? It looks almost like yours (with out the yield) or base case? Did what am I looking over?
Nix
I'll name some. First, "Subordinates" what is that? It implies a collection, but you treat it as an individual. Second, the choice of accumulating over yielding. Third, the empty check which is not necessary....
Will
Easy killer remember the PSUDO tag. The first was a typo... which i fixed, Second you are correct which i already noted above, and third the empty check is only not necessary if you assume Subordinates is non null. If the Subordinates property is nullable then it would be *very* necessary.
Nix
Thanks so much!
AndreMiranda