c# - 从列表中初始化嵌套对象

标签 c# algorithm nested-loops

我有一个整数列表(Levels)。我想初始化一个名为 myFilter 的嵌套过滤器对象,如下所示(Filter 是一个具有两个属性的类:ValueNextFilter):

var myFilter  = new Fliter{
     Value = Levels[0],
     NextFilter = new Filter{
         Value = Levels[1],
         NextFilter = new Filter{
             Value = Levels[2],
             NextFilter = new Filter{
                 Value = Levels[n],
                 NextFilter = null
             }
        }
    }

}

Levelcount 不是静态的,取决于输入列表(我有一个生成 Level 的多选列表) 我怎样才能做到这一点?

最佳答案

这是使用 recursion 的经典事件- 调用自身的方法技术:

public static Filter CreateFilter(List<int> values) => values.Any() ? new Filter //If the list contains elements, create the filter
{
    Value = values.First(), //assign the first item of the values to the value property
    NextFilter = CreateFilter(values.Skip(1).ToList()) //Create the rest of the nested object with the rest of the values
} : null; //If there aren't any items left in the list, return null and stop the recursion

您当然也可以在构造函数中执行此操作:

public Filter(List<int> values)
{
    if (!values.Any()) return;
    Value = values.First();
    NextFilter = values.Count > 1 ? new Filter(values.Skip(1).ToList()) : null;
}

有关递归的更多信息,请查看:https://www.dotnetperls.com/recursion ,有关嵌套类的更多信息,请阅读:https://www.dotnetperls.com/nested-class .


关于递归的更多信息:

您实际上可以通过递归实现一切——您甚至不需要循环。这就是为什么像 Haskell 这样的语言不存在循环的原因。 最简单的递归函数是:

public static void EndlessLoop()
{
    //Loop body
    EndlessLoop();
}

但是,即使是 Resharper 也建议将其转换为循环: Resharper suggestion

另一个例子,如果你想得到一个列表的总和,你可以这样做:

public static int Sum(List<int> summands) => summands.Count > 0
    ? summands.First() + Sum(summands.Skip(1).ToList())
    : 0;

但是这些示例在 C# 中没有用,因为 C# 不是函数式编程语言,这导致递归比循环慢。此外,递归通常会导致 StackOverflowException(适用于此站点)。如果你运行无限循环递归,它甚至不需要一秒钟就可以让你的堆栈变满。

这样做的原因是,C# 将调用方法的地址添加到堆栈。如果一个方法被调用的非常频繁(并且在 1 秒内进行了很多递归调用),就会有很多地址被添加到堆栈中,以至于溢出。

但是我仍然认为,即使这些示例在 c# 中没有用,但能够处理递归是非常有用的。例如,递归是探索目录结构的唯一方法,例如获取所有文件:

public static List<FileInfo> GetAllFiles(DirectoryInfo directory) => directory.GetFiles()
    .Concat(directory.GetDirectories().SelectMany(GetAllFiles))
    .ToList();

而且,如您所见,这是从列表中正确填充嵌套类的唯一方法。

关于c# - 从列表中初始化嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570126/

相关文章:

javascript - 为表中的每一行循环两个数组

c# - 在 for 中声明一个数组

c# - 如何重命名 XML 序列化列表 <string> 中使用的子 XML 元素?

c# - 创建运行时确定类型实例的最佳方法

java - 使用红黑树的字典 - 删除错误

c# - 如何使用 C# 将二维数组插入数据库

c# - C# 中的 BesselK 函数

java - AVL树,java,继任者,前任

database - WP7 - 在数据库中存储坐标

java - Java 中的正则表达式和字符串数组