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 });
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.
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.
Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With