遍历时计算嵌套列表 Objects

Counting Nested List Objects While Traversing

我正在用 C# 开发一个项目,其中有一个 object 属性,其中一个名为 Children,与 parent object.例如:

public class ObjectInformation
{
   public string FullName {get; set;}
   public string FriendlyName {get; set;}
   public List<ObjectInformation> Children {get;}
}

而且我已经有一种方法可以将根 object 展平成一个简单的列表:

public static IEnumerable<ObjectInformation> Flatten(List<ObjectInformation> objs)
{
   var localCopy = Helpers.General.DeepCopy(objs);
   var finalList = new List<ObjectInformation>();
   foreach(var obj in localCopy)
   {
      if(obj.Children.Count > 0)
      {
         finalList.AddRange(Flatten(obj.Children));
         obj.Children.Clear();
      }

      obj.Parent = null;
      finalList.Add(obj);
   }

   return finalList;
}

我知道上述方法可能还可以改进,但现在可以用了。但是,我现在要做的是遍历嵌套列表并输出数据,同时根据嵌套级别缩进行。

举个例子,假设根 object 有两个 object,第一个有一个 child,第二个有一个 child,其中还有一个 child。我希望输出是这样的:

FullName of Root Object 1
   FullName of Child 1 of Root Object 1
FullName of Root Object 2
   FullName of Child 1 of Root Object 2
      FullName of Child 1 of Child 1 of Root Object 2

要进行缩进,我需要某种计数器来确定层级的嵌套深度。我使用递归方法将 运行 保留在问题中,因为在每次调用时,变量都会被重置。我在想,也许我需要使用静态变量来跟踪嵌套级别。我看到的问题是,当它向上移动时,静态变量仍将具有其达到的最深级别的值。

我有点不知道如何处理这个问题,尽管我确信这可能是一个我目前无法想象的简单解决方案;我一般不会 use/need 递归,所以我没有很多实际使用它的经验。

任何 help/suggestions 您提供的任何东西都将不胜感激。

谢谢

我会推荐一种获取对象并使用已定义的 space 打印每个对象的方法。递归调用会增加 x 数量的 space 每次你深入对象。

    public static void Print(this ObjectInformation parent, int spacing = 2)
    {
        Console.WriteLine($"{new string(' ', spacing)}{parent.FullName}");
        foreach (ObjectInformation child in parent.Children)
        {
            child.Print(spacing + 2);
        }
    }

我尝试了这个作为练习并得到了有效的结果。

public void PrintInfoList(IEnumerable<ObjectInformation> list)
    {
        var result = string.Join("\n", list.Select(item => GetPrintedFormat(item)));
        Console.WriteLine(result);
    }

    public string GetPrintedFormat(ObjectInformation info)
    {
        string printedFormat = string.Empty;
        printedFormat = $"Fullname of {info.FriendlyName} - {info.FullName}";
        if (info.Children != null && info.Children.Any())
        {
            childCount++;
            _formatter = $"\n{string.Empty.PadRight(childCount, '\t')}";
            printedFormat += $"{_formatter}{string.Join(_formatter, info.Children.Select(child => GetPrintedFormat(child)))}";
        }
        else
            if (childCount > 0) childCount--;

        return printedFormat;
    }

这是经过测试的工作解决方案。让我知道你对此的看法。

但我也喜欢投票给@Jawad 最简单的方式。 (鼓掌)