Linq extension method, how to find child in collection recursive

前端 未结 6 993
无人共我
无人共我 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条回答
  •  萌比男神i
    2021-02-07 15:06

    Here is a generic solution that will short-circuit traversal of the hierarchy once a match is found.

    public static class MyExtensions
    {
        public static T FirstOrDefaultFromMany(
            this IEnumerable source, Func> childrenSelector,
            Predicate condition)
        {
            // return default if no items
            if(source == null || !source.Any()) return default(T);
    
            // return result if found and stop traversing hierarchy
            var attempt = source.FirstOrDefault(t => condition(t));
            if(!Equals(attempt,default(T))) return attempt;
    
            // recursively call this function on lower levels of the
            // hierarchy until a match is found or the hierarchy is exhausted
            return source.SelectMany(childrenSelector)
                .FirstOrDefaultFromMany(childrenSelector, condition);
        }
    }
    

    To use it in your case:

    var matchingProduct = products.FirstOrDefaultFromMany(p => p.children, p => p.Id == 27);
    

提交回复
热议问题