var maxId = personList.SelectManyRecursive(p => p.Children).Max(p => p.Id);
5
我通过添加另一个级别来轻松切换你的场景 . 如果这没有帮助,请发布您的数据对象的示例 .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace App
{
public enum ID{
one, two, three, four, five, six, seven, eigth, nine, ten
}
public class Person
{
public ID id;
public List<Person> children;
public Person(ID id, List<Person> children)
{
this.id = id;
this.children = children;
}
}
class Program
{
private static List<Person> BuildScenario()
{
return new List<Person>{
new Person(ID.one, new List<Person>()),
new Person(ID.two, new List<Person>{
new Person(ID.three, new List<Person>{
new Person(ID.ten, new List<Person>())
}),
new Person(ID.four, new List<Person>())
}),
new Person(ID.five, new List<Person>{
new Person(ID.six, new List<Person>()),
new Person(ID.seven, new List<Person>()),
new Person(ID.eigth, new List<Person>())
})
};
}
static void Main(string[] args)
{
List<Person> scenario = BuildScenario();
Console.WriteLine(CountIDs(scenario).ToString());
Console.WriteLine(GetMaxID(scenario).ToString());
while(true);
}
private static int CountIDs(List<Person> scenario)
{
int count = 0;
foreach (Person person in scenario)
{
count += 1 + CountIDs(person.children);
}
return count;
}
private static ID GetMaxID(List<Person> scenario)
{
ID maxid = 0;
foreach(Person person in scenario)
{
ID childmax = GetMaxID(person.children);
if (person.id > maxid) maxid = person.id;
if (childmax > maxid) maxid = childmax;
}
return maxid;
}
}
}
2 回答
您可以尝试Concat和SelectMany的组合(仅's assuming it'只嵌套一个级别):
UPDATE
如果您有多个嵌套级别,您还可以编写一个扩展方法来使
SelectMany
递归:这不会处理循环引用,它的行为也不同于
SelectMany
,它还返回源集合本身中的项目(因此您可能想要更改名称),但我认为它可以完成这项工作 . 你可以很容易地使用它:我通过添加另一个级别来轻松切换你的场景 . 如果这没有帮助,请发布您的数据对象的示例 .