Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the property name from the params Func<T, string>[] lambda expression

Tags:

c#

lambda

I have the following class to export data to 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);
    }
}

Which I use like this :

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

And I get:

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

etc..

I the result I want is to use the property name for example FirstName and LastName in this example as column headers:

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

Any clue on how to modify the lambda expression to acomplish this?

like image 479
Marc Avatar asked Oct 20 '22 08:10

Marc


1 Answers

Instead of a Func<>, you'll need to change your parameter type to Expression<Func<>>, instructing C# to construct an expression tree based on the lambda expression that's provided.

Then, something like this should work:

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);
}
like image 195
StriplingWarrior Avatar answered Oct 21 '22 23:10

StriplingWarrior