Skip to content

Instantly share code, notes, and snippets.

@lawrence-laz
Created June 15, 2022 11:27
Show Gist options
  • Save lawrence-laz/40098310b200860db5e9823c845e531e to your computer and use it in GitHub Desktop.
Save lawrence-laz/40098310b200860db5e9823c845e531e to your computer and use it in GitHub Desktop.
EnumerableExtensions
public static class EnumerableExtensions
{
public static IEnumerable<TResult> SelectManyDescending<TCollection, TResult>(
this IEnumerable<TCollection> enumerable,
Func<TCollection, IEnumerable<TResult>> resultSelector,
Func<TCollection, IEnumerable<TCollection>> collectionSelection)
{
if (enumerable is null)
{
return Enumerable.Empty<TResult>();
}
if (resultSelector is null)
{
throw new ArgumentNullException(nameof(resultSelector));
}
if (collectionSelection is null)
{
throw new ArgumentNullException(nameof(collectionSelection));
}
var results = Enumerable.Empty<IEnumerable<TResult>>();
foreach (var collection in enumerable)
{
results = results.Append(resultSelector(collection));
var collections = collectionSelection(collection);
results = results.Append(SelectManyDescending(collections, resultSelector, collectionSelection));
}
return results.SelectMany(result => result);
}
}
public record TestTreeCollection<T>(T[] Values, TestTreeCollection<T>[] Children);
public class EnumerableExtensions
{
[Fact]
public void SelectManyDescending_WithSimpleTree_ShouldReturnAllElementsInSingleCollection()
{
// Arrange
var tree = new TestTreeCollection<int>[]
{
new(
new[] { 1, 2, 3 },
new TestTreeCollection<int>[]
{
new(
new[] { 4, 5 },
new TestTreeCollection<int>[]
{
new(new[] { 6, 7 }, null)
}),
new(new[] { 8 }, null),
}),
new(
new[] { 9, 10 },
new TestTreeCollection<int>[] { new(new[] { 11 }, null) }),
};
var expected = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
// Act
var actual = tree.SelectManyDescending(node => node.Values, node => node.Children);
// Assert
actual.Should().BeEquivalentTo(expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment