Perl-like-Map in C#
If you know a little bit of Perl, you probably know the map function (perldoc -f map).
Map takes an expression E and a list L, transforms the elements of L using the expression E and returns a new list with the transformed items. A short example:
my @words = ('foo', 'bar', 'perl', 'is', 'cool');
my @firsts = map { substr($_, 0, 1) } @words;
The above code takes @words and transforms its elements into a list containing only the first letter of each word in @words. (At all perl monks ou there: i know that there are more simple ways to achieve that
Anyway, i tried to achieve the above functionalty in C#. It kinda works by using extensions on IEnumerable:
public static IEnumerable<TResult> Map<TSource, TResult>(this IEnumerable<TSource> collection, Func<TSource, TResult> converter)
{
if(collection == null)
return null;
List<TResult> retval = new List<TResult>();
foreach (TSource s in collection)
retval.Add(converter(s));
return retval;
}
That’s about it. Last but not least, the above example in a csharpish-way
string[] words = new string[] { "foo", "bar", "perl", "is", "cool", "but", "csharp", "is", "too" };
IEnumerable<char> firsts = words.Map(delegate(string s) { return s.Substring(0, 1); });
// or more .NET 3 style
var firsts = words.Map(s => s.Substring(0, 1));
NICE!
Advertisement