用id递归遍历树,同时添加到列表中
本文关键字:添加 列表 id 递归 遍历 | 更新日期: 2023-09-27 18:15:15
我怎么能递归地遍历我的树与Id,终止当它击中根而添加到List<User>
?我尝试过ref和out的不同组合,没有运气。
我试图修改dotnetpearls示例:
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);
}
到像这样的东西:
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;
}
AddRange
是一次添加几个对象,而您正在添加单个int
元素。它期望list
,而您提供的是int
。
用userIds.Add
代替