radbyx
radbyx

Reputation: 9670

Traverse tree recursively with id while adding to a list

How can I traverse my tree recursively upwards with an Id that terminate when it hit the root while adding to a List<User> ? I have tryed difference combinations with ref and out, with no luck.

I have tryed to modify dotnetpearls example:

static int Recursive(int value, ref int count)
{
    count++;
    if (value >= 10)
    {
        // throw new Exception("End");
        return value;
    }
    return Recursive(value + 1, ref count);
}

static void Main()
{
    //
    // Call recursive method with two parameters.
    //
    int count = 0;
    int total = Recursive(5, ref count);
    //
    // Write the result from the method calls and also the call count.
    //
    Console.WriteLine(total);
    Console.WriteLine(count);
}

To something like this:

static void Main(string[] args)
{
    List<int> userIds = new List<int>();
    Recursive(5, ref userIds);

    Console.WriteLine(userIds);
    Console.ReadKey();
}

static int Recursive(int nodeId, ref List<int> userIds)
{
    userIds.AddRange(GetPersonIdsOnThisNode(nodeId)); // Error: Argument type 'int' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<int>'
    if (nodeId >= 10)
    {
        return nodeId; // I don't care about the return value. I only care about populating my list of userId's.
    }
    return Recursive(nodeId + 1, ref userIds);
}

static int GetUserIdsOnThisNode(int nodeId)
{
    return 3;
}

Upvotes: 0

Views: 340

Answers (1)

MaPi
MaPi

Reputation: 1601

AddRange is to add several objects at once, and you are adding a single int element. It's expecting a list, and you are providing an int.

Use userIds.Add instead.

Upvotes: 2

Related Questions