Created
July 20, 2015 08:51
-
-
Save piers7/7632dcaf8066c4b03578 to your computer and use it in GitHub Desktop.
Recursive Projection in Linq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Performs a projection on a heirachical sequence, without flattening | |
/// </summary> | |
/// <remarks>ie given an input type of X, each item of which has children which are also of type X, | |
/// execute a single selector across all X in the tree to retrieve a new target heirachy | |
/// </remarks> | |
public static IEnumerable<TOut> SelectRecurse<TIn,TOut>(IEnumerable<TIn> items, Func<TIn, IEnumerable<TIn>> childSelector, Func<TIn, IEnumerable<TOut>, TOut> selector){ | |
foreach(var item in items){ | |
var children = childSelector(item); | |
var childrenMapped = SelectRecurse(children, childSelector, selector); | |
var output = selector(item, childrenMapped); | |
yield return output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anytime I searched for 'recursive projection in Linq' I came across solutions that involved flattening, and (basically) projecting the flattened output. I needed to project but retain the hierarchy, ie project from one object graph to another, but do so as a simple lambda.