我有以下类将数据导出到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表达式以实现此目的的任何线索?
答案 0 :(得分:3)
而不是Func<>
,您需要将参数类型更改为Expression<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);
}