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
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);