我可以使用Action <T>执行递归搜索并返回指定属性的IEnumerable吗?

djd*_*d87 1 linq generics action c#-4.0

我编写了以下代码用于StructureId从以下位置检索s IEnumerable<Structure>:

Action<Structure> recurse = null;
List<int> structureIds = new List<int>();
recurse = (r) =>
{
    structureIds.Add(r.StructureId);
    r.Children.ForEach(recurse);
};

IEnumerable<Structure> structures = GetStructures();
structures.ForEach(recurse);
Run Code Online (Sandbox Code Playgroud)

我真的很喜欢这个通用,所以我可以使用它与任何IEnumerable,即:

public static IEnumerable<TType> GetPropertyValues<TType, TPropertyType>(
    this IEnumerable<TType> this, <Property Declaration>)
{
    // Generic version of the above code?
}
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?

Amy*_*y B 5

Action不是很Linq'ish.Func相反怎么样?(未经测试的代码)

public static IEnumerable<TProp> RecurseSelect<TSource, TProp>(
  this IEnumerable<TSource> source,
  Func<TSource, TProp> propertySelector,
  Func<TSource, IEnumerable<TSource>> childrenSelector
)
{
  foreach(TSource x in source)
  {
    yield return propertySelector(x);
    IEnumerable<TSource> children = childrenSelector(x);
    IEnumerable<TProp> values = children.RecurseSelect(propertySelector, childrenSelector);
    foreach(TProp y in values)
    {
      yield return y;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后

IEnumerable<Structure> structures = GetStructures();
IEnumerable<int> structureIds = structures.RecurseSelect(
  s => s.StructureId,
  s => s.Children);
Run Code Online (Sandbox Code Playgroud)