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 });
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.
See more on this question at Stackoverflow