C # lambda expressions as function arguments

Recently, I was diving in lambda expressions, and there was a certain functionality that I wanted to learn, but simply could not create heads or tails.

Suppose there is 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 possibly distract all this operation in the handler method so that I can do this:

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

How can I start writing this method? I envision a signature declaration somehow like:

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

but I don’t know how to indicate that I expect a lambda expression as an argument to a method, and how it exactly translates to the method body.

Can someone show me how to create the MakeArray() function above? I am pretty sure that as soon as I see how to do this, I can pick it up from there.

EDIT

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

+17
generics c # lambda
Mar 22 '11 at 19:30
source share
5 answers
 public static U[] MakeArray<T, U>(this IEnumerable<T> @enum, Func<T, U> rule) { return @enum.Select(rule).ToArray(); } 
+16
Mar 22 '11 at 19:34
source share

Try to execute

 U[] MakeArray<T,U>(Func<T, U> projection) where T : IEntity { ... } 

When passing lambdas as arguments, you usually want the match parameter to be a delegate. In most cases, you should simply use the appropriate Action<> or Func<> value. The first is for emptiness returning lambdas, and the second is for those that return values.

+13
Mar 22 2018-11-21T00:
source share

You are looking for Action<> and Func<> .

+2
Mar 22 2018-11-21T00:
source share

You can use the Func and Action classes. Check out the LINQ Where function example: http://msdn.microsoft.com/en-us/library/bb534803.aspx

+2
Mar 22 '11 at 19:33
source share

You can create an extension

 public static class MakeArrayExtension { public static U[] MakeArray<T, U>(this IEnumerable<T> collection, Func<T,U> func) { return collection.Select(func).ToArray(); } } 

And then use it like this:

 List<A> foo; // assuming this is populated string[] bar = foo.MakeArray<A,string>(x => x.StringProperty); 
+1
Mar 22 '11 at 19:40
source share



All Articles