考虑这个类:
public class Column<T>
{
public string Header { get; set; }
public Func<T, string> ValueExpression { get; set; }
}
这样使用:
var columns = new List<Column<Employee>>
{
new Column<Employee> {Header = "Employee Id", ValueExpression = e => e.EmployeeID.ToString()},
new Column<Employee> {Header = "Name", ValueExpression = e => e.FirstName + " " + e.LastName},
new Column<Employee> {Header = "Employee Birthday Year", ValueExpression = e => e.BirthDate.HasValue ? e.BirthDate.Value.Year.ToString() : ""},
new Column<Employee> { Header = "test", ValueExpression = e => e.Address}
}
我想在 IQueryable 上执行 .Select() 以使其仅从数据库中检索所需的字段。
所以我想做这样的事情:
var expressions = columns.Select(c => c.ValueExpression).Combine();
IQueryable<Employee> employees = EmployeeRepository.GetEmployees();
employees = employees.Select(expressions);
只有“Combine()”显然不存在.. :-)
最佳答案
public static Func<T, U[]> Combine<T, U>(this Func<T, U>[] functions) {
return t => functions.Select(fun => fun(t)).ToArray();
}
我会声明通用 IEnumerable<Func<T, U>>
而不是数组:
public static Func<T, IEnumerable<U>> Combine<T, U>(this IEnumerable<Func<T, U>> functions)
{
return t => functions.Select(fun => fun(t));
}
如评论中所述,这不太可能直接与 LINQ to SQL 一起使用。但是,您可以通过执行 .AsEnumerable()
来获取 LINQ to SQL 结果。并在客户端处理其余部分。
关于c# - 将 Func<T, string>[] 转换成 Func<T, string[]>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/887830/