使用foreach循环项初始化List

时间:2016-01-12 15:21:23

标签: c# list

我正在尝试设置类型为List的对象属性的值,并使用foreach将项目添加到列表中进行初始化,例如。

var sessionPlanner = new SessionPlannerDTO()
        {
            Age = "",
            NumberOfPlayers = session.numberOfPlayers.Value,
            MedicalInformation = "",
            PlayerNeeds = "",
            SessionDate = session.daySessionDate.Value,
            Location = session.Location.locationName,
            PracticeView = new List<PracticeViewDTO>(foreach(var practice in session.Sessions){
                new PracticeViewDTO(){AbilityLevel = practice.ActivityPlan.abilityLevel.Value,
                ActivityUrl = practice.ActivityPlan.activityUrl,
                EquipmentNeeds = practice.ActivityPlan.equipmentNeeds,
                FacilityNeeds = practice.ActivityPlan.activityNeeds,
                HealthAndSafety = practice.ActivityPlan.healthAndSafetyIssues,
                SessionTitle = practice.ActivityPlan.activityName
                };
            })

        };

练习视图是我试图通过将其作为列表而不执行以下操作来实现的:

var practiceViewList = new List<PracticeViewDTO>();
        foreach(var practice in session.Sessions)
        {
            var practiceX = new PracticeViewDTO()
            {
                AbilityLevel = practice.ActivityPlan.abilityLevel.Value,
                ActivityUrl = practice.ActivityPlan.activityUrl
            };
            practiceViewList.Add(practiceX);
        }

1 个答案:

答案 0 :(得分:1)

您不能使用除对象或集合初始值设定项中的赋值之外的其他代码。所以你的foreach()将无法编译。

使用session.Sessions.Select()将源实体映射到DTO,使用ToList()创建结果列表:

sessionPlanner = new SessionPlannerDTO
{
    Age = "",
    // ...
    PracticeView = session.Sessions.Select(s =>
        new PracticeViewDTO
        {
            AbilityLevel = s.ActivityPlan.abilityLevel.Value,
            // ...
        }).ToList()
};

您也可以考虑使用AutoMapper,而不是手写映射代码。