Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 11, 2016 10:37
Show Gist options
  • Save miklund/139c93a005595933334c to your computer and use it in GitHub Desktop.
Save miklund/139c93a005595933334c to your computer and use it in GitHub Desktop.
2012-06-03 Map - 7 higher order functions
# Title: Map - 7 higher order functions
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/06/03/map-7-higher-order-functions.html
private int Double(int i)
{
return i * 2;
}
Map(Double, new [] {1, 2, 3});
public static IEnumerable<U> Map<T, U>(Func<T, U> fn, IEnumerable<T> list)
{
if (fn == null)
{
throw new ArgumentNullException("fn", "Supplied function to Map is not allowed to be null");
}
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Map is not allowed to be null");
}
foreach (var item in list)
{
yield return fn(item);
}
}
Map(i => i.ToString(), new[] {1, 2, 3})
-> ["1", "2", "3"]
var people = new[]
{
new Person { FirstName = "Mikael", Surname = "Lundin" },
new Person { FirstName = "John", Surname = "Doe" },
new Person { FirstName = "Foo", Surname = "Bar" },
};
var names = people.Select(p => p.FirstName + " " + p.Surname);
/*
=> new [] {
"Mikael Lundin",
"John Doe",
"Foo Bar"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment