Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 11, 2016 20:23
Show Gist options
  • Save miklund/6bbcb6ac19c2e444cf77 to your computer and use it in GitHub Desktop.
Save miklund/6bbcb6ac19c2e444cf77 to your computer and use it in GitHub Desktop.
2012-06-21 Collect - 7 higher order functions
# Title: Collect - 7 higher order functions
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/06/21/collect-7-higher-order-functions.html
private class BlogPost
{
public IEnumerable<Comment> Comments { get; private set; }
public static IEnumerable<BlogPost> All()
{
// return SELECT blogpost.* FROM db
}
}
var blogPosts = BlogPost.All();
var comments = blogPosts.Collect(post => post.Comments);
public static IEnumerable<U> Collect<T, U>(Func<T, IEnumerable<U>> fn, IEnumerable<T> list)
{
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Collect is not allowed to be null");
}
if (fn == null)
{
throw new ArgumentNullException("fn", "Supplied function to Collect is not allowed to be null");
}
foreach (var item1 in list)
foreach (var item2 in fn(item1))
{
yield return item2;
}
}
public static IEnumerable<U> Collect<T, U>(this IEnumerable<T> list, Func<T, IEnumerable<U>> fn)
{
return Collect(fn, list);
}
var numbers = new[]
{
new[] { 1, 2, 3 },
new[] { 4, 5, 6 },
new[] { 7, 8, 9 },
};
var flat = numbers.Collect(arr => arr);
// 1, 2, 3, 4, 5, 6, 7, 8, 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment