【发布时间】:2013-09-14 00:13:09
【问题描述】:
我正在尝试创建一个 linq 扩展方法,该方法将路径返回到选定节点。
节点 Item4 的路径将产生 - { Item1, Item2, Item4 }
节点 Item3 的路径将产生 - { Item1, Item3 }
public class Item
{
public int Id { get; set; }
public IList<Item> Items { get; set; }
}
Item1
Item2
Item4
Item3
调用代码
var path = myItem.Items
.Path(e => e.Items, e => MyPredicateCondition())
.ToList();
扩展方法
public static IEnumerable<T> Path<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Predicate<T> condition)
{
if (source == null || !source.Any()) return default(T);
var attempt = source.FirstOrDefault(t => condition(t));
if (!Equals(attempt, default(T))) return attempt;
var items = source.SelectMany(childrenSelector)
.Path(childrenSelector, condition)
.ToList();
return attempt;
}
我的问题不是找到实际的节点,而是返回节点递归地将树备份到根节点。数据结构应该保持原样 - 即我不希望 Item 引用它的 parent item。
注意:代码当前无法编译,因为我正在尝试通过其他方式使用 IEnumerable yield 等。
效率不是问题,因为它将用于 3 或 4 个级别,每个级别只有几个项目。
【问题讨论】:
-
请提供示例输入和预期输出以澄清问题。
-
对不起,我错过了层次结构。我想就是这样。