如何从参数Func<;T、 字符串>;[]lambda表达式

本文关键字:gt 字符串 表达式 lambda Func 参数 lt | 更新日期: 2023-09-27 17:59:04

我有以下类可以将数据导出到CSV:

public class CsvResult<T> : FileResult where T : class
{
    private const string SEPARATOR = ",";
    public IEnumerable<T> Data { get; private set; }
    public Func<T, string>[] Columns { get; private set; }
    public CsvResult(IEnumerable<T> data, params Func<T, string>[] columns)
        : base("text/csv")
    {
        Data = data;
        Columns = columns;
        FileDownloadName = "Export.csv";
    }
    protected override void WriteFile(HttpResponseBase response)
    {
        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", FileDownloadName));
        WriteColumns(response);
        WriteData(response);
    }
    private void WriteData(HttpResponseBase response)
    {
        foreach (var dataItem in Data)
        {
            foreach (var column in Columns)
                WriteCsvCell(response, column(dataItem));
            response.Write(Environment.NewLine);
        }
    }
    private void WriteColumns(HttpResponseBase response)
    {
        foreach (var column in Columns)
            WriteCsvCell(response, column.ToString());
        response.Write(Environment.NewLine);
    }
    private void WriteCsvCell(HttpResponseBase response, string text)
    {
        // Surround with quotes + escape quotes within the text
        response.Write("'"" + text.Replace("'"", "'"'"") + "'"");
        response.Write(SEPARATOR);
    }
}

我这样使用:

        if (format == RenderFormat.Csv)
            return new CsvResult<User>(
                users,
                u => u.FirstName,
                u => u.LastName);

我得到:

"System.Func`2[HDO.Application.Model.Models.User,System.String]","System.Func`2[HDO.Application.Model.Models.User,System.String]",
"FirstName1","LastName1",
"FirstName2","LastName2",

等等。。

我想要的结果是使用属性名称,例如本例中的FirstName和LastName作为列标题:

"FirstName", "LastName", <--------Headers
"FirstName1","LastName1", <---------Data row 1
"FirstName2","LastName2",<---------Data row 2

有关于如何修改lambda表达式以使其复杂化的线索吗?

如何从参数Func<;T、 字符串>;[]lambda表达式

您需要将参数类型更改为Expression<Func<>>,而不是Func<>,指示C#基于所提供的lambda表达式构建表达式树。

然后,像这样的东西应该会起作用:

private void WriteColumns(HttpResponseBase response)
{
    var columnNames = columns
        .Select(lambda => {
            var expressionBody = lambda.Body;
            var memberExpression = (MemberExpression)expressionBody;
            var memberName = memberExpression.Member.Name;
            return memberName;
        })
       .ToList();
    foreach (var column in Columns)
        WriteCsvCell(response, column.ToString());
    response.Write(Environment.NewLine);
}