不确定怎么称呼它,但是假设你有一个类看起来像这样:
class Person
{
public string Name;
public IEnumerable<Person> Friends;
}
你现在有一个人,想要递归地“展开”这个结构,以便最终得到一个没有重复的所有人的列表。
你会怎么做?我已经做了一些看起来可以工作的东西,但我很好奇其他人会如何做,特别是是否有内置于Linq中的东西可以巧妙地解决这个小问题 :)
以下是我的解决方案:
public static IEnumerable<T> SelectRecursive<T>(this IEnumerable<T> subjects, Func<T, IEnumerable<T>> selector)
{
// Stop if subjects are null or empty
if(subjects == null)
yield break;
// For each subject
foreach(var subject in subjects)
{
// Yield it
yield return subject;
// Then yield all its decendants
foreach (var decendant in SelectRecursive(selector(subject), selector))
yield return decendant;
}
}
以下是使用示例:
var people = somePerson.SelectRecursive(x => x.Friends);
if(!subjects.Any()) yield break;
来完成。 - Oliver