Nested Lambda Expressions

c# expression-trees lambda

Question

Does anyone have any idea how I call a lambda expression from within a lambda expression?

If I have:

public class CourseViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static Expression<Func<Course, CourseViewModel>> AsViewModel = x =>
        new CourseViewModel
        {
            Id = x.Id,
            Name = x.Name,
        }
}

public class StudentViewModel
{
    public int Id { get; set; }
    public string Name{ get; set; }
    public string PreferredCheese { get; set; }
    public IEnumerable<CourseViewModel> Courses { get; set; }

    public static Expression<Func<Student, StudentViewModel>> AsViewModel = x =>
        new StudentViewModel
        {
            Id = x.Id,
            Name = x.Name,
            PreferredCheese = x.PreferredCheese,
            Courses = ???I'd like to call the CourseViewModel.AsViewModel here
        }
}

In the code above rather than writing the AsViewModel expression within the StudentViewModel as:

Courses = new CourseViewModel
{
    Id = x.Id,
    Name = x.Name,
}

I'd like to call CourseViewModel.AsViewModel to allow code re-use and to keep the code converting a Course to a CourseViewModel in the CourseViewModel class. Is this possible?

Popular Answer

You can just use x.Courses.Select(c => CourseViewModel.AsViewModel(c)) So your whole expression would be:

public static Expression<Func<Student, StudentViewModel>> AsViewModel = x =>
        new StudentViewModel
        {
            Id = x.Id,
            Name = x.Name,
            PreferredCheese = x.PreferredCheese,
            Courses = x.Courses.Select(c => CourseViewModel.AsViewModel(c))
        }


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why