Linq extension method, how to find child in collection recursive

前端 未结 6 919
无人共我
无人共我 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:01

    If you want to "sub-iterate" and find a child in a list of Products:

    List
        Product
           Child
           Child
           Child
           Child
        Product
           Child
           Child *find this one
           Child
    

    You can use the existing SelectMany extension method. SelectMany can be used to "flatten" a two-level hierarchy.

    Here's a great explanation of SelectMany: http://team.interknowlogy.com/blogs/danhanan/archive/2008/10/10/use-linq-s-selectmany-method-to-quot-flatten-quot-collections.aspx

    Your syntax would like like this:

    List p = GetProducts(); //Get a list of products
    var child = from c in p.SelectMany(p => p.Children).Where(c => c.Id == yourID);
    

提交回复
热议问题