Linq extension method, how to find child in collection recursive

前端 未结 6 1023
无人共我
无人共我 2021-02-07 14:58

I\'m already familiar with Linq but have little understanding of extension methods I\'m hoping someone can help me out.

So I have this hierarchical collection pseudo cod

6条回答
  •  星月不相逢
    2021-02-07 15:27

    I'm just refactoring dtb's solution to make it more generic. Try this Extension method:

    public static IEnumerable Flatten(this IEnumerable source, Func recursion) where R : IEnumerable
    {
        return source.SelectMany(x => (recursion(x) != null && recursion(x).Any()) ? recursion(x).Flatten(recursion) : null)
                     .Where(x => x != null);
    }
    

    And you can use it like this:

    productList.Flatten(x => x.Children).Where(x => x.ID == id);
    

提交回复
热议问题