考虑这个课程:
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()”显然不存在..: - )
答案 0 :(得分:6)
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结果,并在客户端处理其余部分。