Convert Func <T, string> [] to Func <T, string []>?

Consider this class:

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

used as follows:

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 make .Select () in IQueryable so that it only retrieves the required fields from the database.

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 does not exist .. :-)

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

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

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 the comments, this is unlikely to work directly with LINQ to SQL. However, you can get LINQ to SQL results by running .AsEnumerable()and processing the rest on the client side.

+6
source

Source: https://habr.com/ru/post/1708733/


All Articles