Skip to content

Instantly share code, notes, and snippets.

@piers7
Created July 20, 2015 08:51
Show Gist options
  • Save piers7/7632dcaf8066c4b03578 to your computer and use it in GitHub Desktop.
Save piers7/7632dcaf8066c4b03578 to your computer and use it in GitHub Desktop.
Recursive Projection in Linq
/// <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;
}
}
@piers7
Copy link
Author

piers7 commented Jul 20, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment