programming with esskar

Just another WordPress.com weblog

Perl-like-Map in C#

leave a comment »

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

Written by esskar

February 23, 2010 at 7:14 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.