我整天都在进行这项工作,无法弄清楚如何将其创建为简单的Lambda表达式:
public IReadOnlyList<UserActivity> GetListOfUserActivities()
{
List<UserActivity> userActivities = new List<UserActivity>();
List<Activity> activities = _activityDataAccess.GetActivities();
foreach (var activity in activities)
{
UserActivity userActivity = _mapper.Map<UserActivity>(activity);
userActivity.Parent = this;
userActivities.Add(userActivity);
}
return userActivities;
}
总而言之:
这是我要去的地方
activities
.ConvertAll(act => _mapper.Map<UserActivity>(act))
.Select(uac => uac.Parent = this).ToList();
但这真的不开心!
答案 0 :(得分:2)
我不太了解您对this
所做的事情,但您做不到:
为UserActivity
创建一个新的构造函数,该构造函数接受parent和传入的Activity
对象的参数,并在其中进行映射:
public UserActivity(Activity activity, Object parent){
this = _mapper.Map<UserActivity>(activity);
this.Parent = parent;
}
然后在lambda中进行选择,以将对象重新添加到列表中:
var userActivities = activities.Select(i => new UserActivity(i, parentObject)); // parentObject == this?
答案 1 :(得分:1)
那呢?
activities
.Select(act =>
{
var userActivity = _mapper.Map<UserActivity>(act);
userActivity.Parent = this;
return userActivity;
}).ToList();
答案 2 :(得分:0)
我试图变得太聪明(或者可能不是这样):
public IReadOnlyList<UserActivity> GetListOfUserActivities()
{
List<UserActivity> userActivities = _activityDataAccess.GetActivities().ConvertAll(act => _mapper.Map<UserActivity>(act)).ToList();
userActivities.ForEach(ua => ua.Parent = this);
return userActivities;
}
但是考虑到Johnathan的帖子,即进一步分解问题,我意识到上面的方法是可行的,只需要将其分解为两个语句即可。谢谢。