How to search Hierarchical Data with Linq

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

    Some further variants on the answers of It'sNotALie., MarcinJuraszek and DamienG.

    First, the former two give a counterintuitive ordering. To get a nice tree-traversal ordering to the results, just invert the concatenation (put the "source" first).

    Second, if you are working with an expensive source like EF, and you want to limit entire branches, Damien's suggestion that you inject the predicate is a good one and can still be done with Linq.

    Finally, for an expensive source it may also be good to pre-select the fields of interest from each node with an injected selector.

    Putting all these together:

    public static IEnumerable Flatten(this T source, Func> children
        , Func selector
        , Func branchpredicate = null
    ) {
        if (children == null) throw new ArgumentNullException("children");
        if (selector == null) throw new ArgumentNullException("selector");
        var pred = branchpredicate ?? (src => true);
        if (children(source) == null) return new[] { selector(source) };
    
        return new[] { selector(source) }
            .Concat(children(source)
            .Where(pred)
            .SelectMany(c => Flatten(c, children, selector, pred)));
    }
    

提交回复
热议问题