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?

1
1
10/14/2014 6:54:16 AM

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))
        }
4
10/13/2014 4:11:05 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow