从列表中初始化嵌套对象

Initialize nested Object from a list

我有一个整数列表 (Levels)。我想初始化一个名为 myFilter 的嵌套过滤器对象,如下所示(Filter 是一个具有两个属性的 class: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 的多 select 列表) 我怎样才能做到这一点?

只需创建一个 Filter 的构造函数,它将获取 Levels 数组作为参数,并将其值设置为级别[0],并初始化 NextFilter = new Filter(level.Skip(1))。像那样的东西。它会递归地初始化你的对象。

这是一个 classic 事件,用于使用 - 调用自身的方法技术:

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, for more information on nested classes read through this: https://www.dotnetperls.com/nested-class


关于递归的更多信息:

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

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

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

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

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

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

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

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

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

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