Get a collection of child positions for a given parent position I am trying to get a complete tree in a single loop using an iterative function. For instance, this is what I have:

var someVariable = GetAllChildPositions(posId) //Method called from a console method.



public ICollection&lt;Position&gt; GetAllChildPositions(int posId)
{
    ICollection&lt;Position&gt; posCollection = new Collection&lt;Position&gt;();
    posCollection= GetChildPos(posId,posCollection);
    return posCollection;
}

public ICollection&lt;Position&gt; GetChildPos(int posId, ICollection&lt;Position&gt; posCollection) 
{
    var posObject= serviceRepo.Position.GetById(posId);
    posCollection.Add(posObject);
    if (serviceRepo.Position.GetAll().Where(x =&gt; x.ParentPosId == posId).Any())
    {
        var childPositions = serviceRepo.Position().GetAll().Where(x =&gt; x.ParentPosId == posId);
        foreach (var childPos in childPositions )
        {
            GetChildRows(childPos.Id, posCollection);
        }
    }
    return posCollection;
}


I am trying to get a list/collection child positions for a given parent position Id. This method works quite well and gets the job done albeit a little slowly. I am interested in knowing if there is a better way of doing this.
If Position and Position() in your code is the same and you supposed to call GetChildPos instead of GetChildRows in the inner loop then your code can be significantly simplified:

var someVariable = GetChildPos(posId).ToList();

public IEnumerable&lt;Position&gt; GetChildPos(int posId)
{
    yield return serviceRepo.Position.GetById(posId);

    foreach (var pos in serviceRepo.Position().GetAll()
                                              .Where(x =&gt; x.ParentPosId == posId)
                                              .SelectMany(x =&gt; GetChildPos(x.Id)))
    {
        yield return pos;
    }
}


Also it can improve performance because in your original code you do this instructions

serviceRepo.Position().GetAll().Where(x =&gt; x.ParentPosId == posId)


two times that can cause slowing down if some method in this chain is not lazy and executes heavy code even for Any().