How to search Hierarchical Data with Linq

前端 未结 8 667
心在旅途
心在旅途 2020-12-03 11:43

I need to search a tree for data that could be anywhere in the tree. How can this be done with linq?

class Program
{
    static void Main(string[] args) {

         


        
8条回答
  •  遥遥无期
    2020-12-03 12:12

    Simple:

    familyRoot.Flatten(f => f.Children);
    //you can do whatever you want with that sequence there.
    //for example you could use Where on it and find the specific families, etc.
    
    IEnumerable Flatten(this T source, Func> selector)
    {
        return selector(source).SelectMany(c => Flatten(selector(c), selector))
                               .Concat(new[]{source});
    }
    

提交回复
热议问题