tar*_*713 8 c# lambda delegates
我正在IList上构建一个扩展方法,以便能够输出作为列表传递给它的任何对象的指定属性,并将其输出为CSV字符串.看起来像:
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
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我必须将此方法称为:
// 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);
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法来传递我的lambda表达式而不必显式声明columns变量,如:
// This doesn't compile
string s = Products.OutputCSVString(new { p => p.Id , p => p.Name });
Run Code Online (Sandbox Code Playgroud)
而不是List<Func<T, string>>使用a Func<T, string>[]并使其成为参数数组:
static string OutputCSVString<T>(this IList<T> list,
params Func<T, string>[] properties)
Run Code Online (Sandbox Code Playgroud)
然后你应该可以打电话:
string s = Products.OutputCSVString(p => p.Id , p => p.Name);
Run Code Online (Sandbox Code Playgroud)
请注意,从C#6开始,您应该能够写:
static string OutputCSVString<T>(this IList<T> list,
params IEnumerable<Func<T, string>> properties)
Run Code Online (Sandbox Code Playgroud)
...这意味着你仍然可以使用它List<Func<T, string>>.
尝试传入params数组
public static string OutputSVString<T>(this IList<T> list, params Func<T, string>[] properties)
{
...
}
Run Code Online (Sandbox Code Playgroud)
这将让你调用它
var s = Products.OutputCSVString(p => p.Id, p => p.Name);
Run Code Online (Sandbox Code Playgroud)
另外,作为建议,放松函数返回对象,然后在组装零件时调用ToString().这样,您可以传入任何属性以包含在CSV列表中,而不仅仅是字符串.
| 归档时间: |
|
| 查看次数: |
953 次 |
| 最近记录: |