gpt4 book ai didi

c# - 如何对采用委托(delegate)列表的函数使用 lambda 表达式

转载 作者:太空狗 更新时间:2023-10-29 18:16:02 27 4
gpt4 key购买 nike

我正在 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
}
}

现在,我必须像这样调用这个方法:

// 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);

有没有更好的方法来传递我的 lambda 表达式而不必显式声明列变量,例如:

// This doesn't compile
string s = Products.OutputCSVString(new { p => p.Id , p => p.Name });

最佳答案

而不是使用 List<Func<T, string>>使用Func<T, string>[]并将其设为 parameter array :

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

那么你应该可以调用:

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

请注意,从 C# 6 开始,您应该能够编写:

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

... 这意味着您仍然可以将它与 List<Func<T, string>> 一起使用

关于c# - 如何对采用委托(delegate)列表的函数使用 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26130160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com