How to search Hierarchical Data with Linq

前端 未结 8 665
心在旅途
心在旅途 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:09

    So, the simplest option is to write a function that traverses your hierarchy and produces a single sequence. This then goes at the start of your LINQ operations, e.g.

        IEnumerable Flatten(this T source)
        {
          foreach(var item in source) {
            yield item;
            foreach(var child in Flatten(item.Children)
              yield child;
          }
        }
    

    To call simply: familyRoot.Flatten().Where(n => n.Name == "Bob");

    A slight alternative would give you a way to quickly ignore a whole branch:

        IEnumerable Flatten(this T source, Func predicate)
        {
          foreach(var item in source) {
             if (predicate(item)) {          
                yield item;
                foreach(var child in Flatten(item.Children)
                   yield child;
          }
        }
    

    Then you could do things like: family.Flatten(n => n.Children.Count > 2).Where(...)

提交回复
热议问题