从列表初始化嵌套对象

时间:2017-04-23 10:44:59

标签: 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
             }
        }
    }

}

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

2 个答案:

答案 0 :(得分:0)

只需构建一个Filter的构造函数,将Levels数组作为参数,将其值设置为level [0],并将init NextFilter设置为new Filter(level.Skip(1))。这样的事情。它会以递归方式初始化您的对象。

答案 1 :(得分:0)

这是使用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();

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

相关问题