Linq extension method, how to find child in collection recursive

前端 未结 6 995
无人共我
无人共我 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条回答
  •  Happy的楠姐
    2021-02-07 15:06

    You can flatten your tree structure using this extension method:

    static IEnumerable Flatten(this IEnumerable source)
    {
        return source.Concat(source.SelectMany(p => p.Children.Flatten()));
    }
    

    Usage:

    var product42 = products.Flatten().Single(p => p.Id == 42);
    

    Note that this is probably not very fast. If you repeatedly need to find a product by id, create a dictionary:

    var dict = products.Flatten().ToDictionary(p => p.Id);
    
    var product42 = dict[42];
    

提交回复
热议问题