将Func []转换为Func ?

时间:2022-06-02 20:51:47

Consider this class:

考虑这个课程:

public class Column<T>
{
    public string Header { get; set; }
    public Func<T, string> ValueExpression { get; set; }
}

used like this:

像这样使用:

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}
              }

I would like to do a .Select() on an IQueryable to make it only retrieve the needed fields from the database.

我想在IQueryable上做一个.Select(),使它只从数据库中检索所需的字段。

So I want to do something like this:

所以我想做这样的事情:

var expressions = columns.Select(c => c.ValueExpression).Combine();
IQueryable<Employee> employees = EmployeeRepository.GetEmployees();
employees = employees.Select(expressions);

Only "Combine()" obviously doesn't exist.. :-)

只有“Combine()”显然不存在.. :-)

1 个解决方案

#1


public static Func<T, U[]> Combine<T, U>(this Func<T, U>[] functions) {
    return t => functions.Select(fun => fun(t)).ToArray();
}

I'd declare that for generic IEnumerable<Func<T, U>> instead of array:

我声明对于通用IEnumerable >而不是数组:

public static Func<T, IEnumerable<U>> Combine<T, U>(this IEnumerable<Func<T, U>> functions)
{
    return t => functions.Select(fun => fun(t));
}

As mentioned in comments, this is not likely to work directly with LINQ to SQL. However, you could grab LINQ to SQL results by doing a .AsEnumerable() and process the rest on client side.

正如评论中所提到的,这不太可能直接与LINQ to SQL一起使用。但是,您可以通过执行.AsEnumerable()来获取LINQ to SQL结果,并在客户端处理其余部分。

#1


public static Func<T, U[]> Combine<T, U>(this Func<T, U>[] functions) {
    return t => functions.Select(fun => fun(t)).ToArray();
}

I'd declare that for generic IEnumerable<Func<T, U>> instead of array:

我声明对于通用IEnumerable >而不是数组:

public static Func<T, IEnumerable<U>> Combine<T, U>(this IEnumerable<Func<T, U>> functions)
{
    return t => functions.Select(fun => fun(t));
}

As mentioned in comments, this is not likely to work directly with LINQ to SQL. However, you could grab LINQ to SQL results by doing a .AsEnumerable() and process the rest on client side.

正如评论中所提到的,这不太可能直接与LINQ to SQL一起使用。但是,您可以通过执行.AsEnumerable()来获取LINQ to SQL结果,并在客户端处理其余部分。