问题描述
有人知道我如何从lambda表达式中调用lambda表达式吗?
Does anyone have any idea how I call a lambda expression from within a lambda expression?
如果我有
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
}
}
在上面的代码中,而不是在StudentViewModel中将AsViewModel表达式编写为:
In the code above rather than writing the AsViewModel expression within the StudentViewModel as:
Courses = new CourseViewModel
{
Id = x.Id,
Name = x.Name,
}
我想调用CourseViewModel.AsViewModel,以允许代码重复使用,并保持将Course转换为CourseViewModel类中的CourseViewModel的代码.这可能吗?
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?
推荐答案
您可以只使用x.Courses.Select(c => CourseViewModel.AsViewModel(c))
,这样您的整个表达式将是:
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))
}
这篇关于嵌套Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!