Linq extension method, how to find child in collection recursive

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

    An alternative solution using the yield to optimize the enumerations needed.

    public static IEnumerable SelectManyRecursive(
        this IEnumerable source,
        Func> childrenSelector)
    {
        if (source == null)
            throw new ArgumentNullException("source");
    
        foreach (var i in source)
        {
            yield return i;
            var children = childrenSelector(i);
            if (children != null)
            {
                foreach (var child in SelectManyRecursive(children, childrenSelector))
                {
                    yield return child;
                }
            }
        }
    }
    

    Then you can find a match by calling something like FirstOrDefault:

        var match = People.SelectManyRecursive(c => c.Children)
                          .FirstOrDefault(x => x.Id == 5);
    

提交回复
热议问题