Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda expressions as function arguments

I've been busy diving into lambda expressions recently, and there's some specific functionality that I've been meaning to learn but just couldn't seem to make heads or tails of.

Suppose that I have the following logic in my code:

List<A> foo; // assuming this is populated
string[] bar = foo.Select<A,string>(x => x.StringProperty).ToArray<string>();

Now, I want to perhaps abstract that whole operation into a handler method so that I can do this instead:

string[] bar = MakeArray<A,string>(foo, x => x.StringProperty);
int[] foobar = MakeArray<A,int>(foo, x => x.IntegerProperty);

How would I go about with writing that method's body? I foresee declaring the signature as something like:

U[] MakeArray<T,U>( /* some lambda magic? */ ) where T : IEntity {}

but I don't know how to specify that I'm expecting a lambda expression as the method argument, and how that translates exactly into the body of the method.

Can anybody show me how to create the MakeArray() function above? I'm pretty sure that once I see how it's done, that I can pick it up from there.

EDIT

As pointed out in the comments, MakeArray() needed a reference to the IEnumerable<>. Updated to reflect that.

like image 684
Richard Neil Ilagan Avatar asked Mar 22 '11 19:03

Richard Neil Ilagan


1 Answers

public static U[] MakeArray<T, U>(this IEnumerable<T> @enum, Func<T, U> rule)
{
    return @enum.Select(rule).ToArray();
}
like image 81
Yuriy Faktorovich Avatar answered Sep 22 '22 08:09

Yuriy Faktorovich