Search code examples
c#linq

c# linq projection into method


I have this simple projection that projects Date to DateDto:

public static IQueryable<DateDto> Projection(this IQueryable<Date> source)
    {
        return source.Select(c => c.Map()).AsQueryable();
    }

    private static DateDto Map(this Date date)
    {
        return new DateDto()
        {
            Id = date.Id,
            EndDate = date.EndDate,
            EndHour = date.EndHour
        };
    }

Although this select query all the fields of the Date table (entity), which is not efficient.

This code snippet select only the three filelds I want, but I would like to move the select into aseparate function. Is it possible?

 public static IQueryable<DateDto> Projection(this IQueryable<Date> source)
    {
        return source.Select(date => new DateDto()
        {
            Id = date.Id,
            EndDate = date.EndDate,
            EndHour = date.EndHour
        }).AsQueryable();
    }

Solution

  • You can write your method to return an Expression<Func<Date, DateDto>>:

    public static IQueryable<DateDto> Projection(this IQueryable<Date> source) =>
        source.Select(MapDate());
    
    private static Expression<Func<Date, DateDto>> MapDate() =>
        date => new DateDto
        {
            Id = date.Id,
            EndDate = date.EndDate,
            EndHour = date.EndHour
        };
    

    You could even just make that a field, to create the expression tree just once:

    private static readonly Expression<Func<Date, DateDto>> MapDate =
        date => new DateDto
        {
            Id = date.Id,
            EndDate = date.EndDate,
            EndHour = date.EndHour
        };
    
    public static IQueryable<DateDto> Projection(this IQueryable<Date> source) =>
        source.Select(MapDate);