Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lambda expressions for a function that takes a list of delegates

I'm building an extension method on IList to be able to output the specified properties of any object passed into it as a list, and output it as a CSV string. It looks like:

public static string OutputCSVString<T>(this IList<T> list, List<Func<T, string>> properties)
{
   foreach (var row in list)
   {
     foreach(var item in properties)
     { 
        // Do the output work, including calling item(row).
     }
      // Output new line
   }
 }

Right now, I have to call this method like:

// Assuming I've populated List <Product> ProductList up above...

var columns = new List<Func<Product, string>>();
columns.Add(x => x.Id);
columns.Add(x => x.Name);

string s = ProductList.OutputCSVString(columns);

Is there a better way to pass in my lambda expressions without having to explicitly declare the columns variable, something like:

// This doesn't compile
string s = Products.OutputCSVString(new { p => p.Id , p => p.Name });
like image 620
tarun713 Avatar asked Sep 30 '14 21:09

tarun713


People also ask

How you can assign a lambda expression to a delegate?

Since a lambda expression is just another way of specifying a delegate, we should be able to rewrite the above sample to use a lambda expression instead of an anonymous delegate. In the preceding example, the lambda expression used is i => i % 2 == 0 . Again, it is just a convenient syntax for using delegates.

What is the difference between lambda expression and delegate?

The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.

Can lambda function evaluate multiple expressions?

Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.

How are an anonymous delegate and a lambda expression related?

Anonymous Method is an inline code that can be used wherever a delegate type is expected. Microsoft introduced Anonymous Methods in C# 2.0 somewhere around 2003. Lambda expression is an anonymous method that you can use to create delegates or expression tree types.


1 Answers

Rather than using a List<Func<T, string>> use a Func<T, string>[] and make it a parameter array:

static string OutputCSVString<T>(this IList<T> list,
                                 params Func<T, string>[] properties)

Then you should be able to call:

string s = Products.OutputCSVString(p => p.Id , p => p.Name);

Note that as of C# 6, you should be able to write:

static string OutputCSVString<T>(this IList<T> list,
                                 params IEnumerable<Func<T, string>> properties)

... which would mean you could still use it with a List<Func<T, string>> as well.

like image 84
Jon Skeet Avatar answered Sep 30 '22 06:09

Jon Skeet