将列表从一个模型组合到另一个模型中?

时间:2014-02-13 17:04:51

标签: c# asp.net-mvc

我有两种不同的型号。一个是viewmodel,另一个是标准模型。我试图将一个模型的结果合并到第二个视图模型中。我被困在循环部分。

var model = new SurveyPageViewModel()
            {
                SurveyId = surveyData.Id,
                Title = surveyData.Title,
                Id = surveyData.Pages[0].Id,
                Questions = new List<QuestionViewModel>()
                {
                    new QuestionViewModel()
                    {
                        // I want to use the data I pulled in my surveyData here.
                    }
                }
            };

型号:

public class SurveyPageViewModel
    {
        public int? SurveyId { get; set; }

        public string Title { get; set; }

        public int? Id { get; set; }

        public List<QuestionViewModel> Questions { get; set; }
    }

 public class QuestionViewModel
    {
        public int? Id { get; set; }

        public string QuestionType { get; set; }

        public string SubType { get; set; }

        public string Text { get; set; }

        public string Value { get; set; }

        public int SortOrder { get; set; }

        public bool IsHidden { get; set; }

        public List<QuestionOptionViewModel> Options { get; set; }
    }

我的其他型号:

public class SurveyPageViewModel
        {
            public int? Id { get; set; }

            public List<QuestionViewModel> Questions { get; set; }
        }

 public class Question
    {
        public int? Id { get; set; }

        public string QuestionType { get; set; }

        public string SubType { get; set; }

        public string Text { get; set; }

        public int SortOrder { get; set; }

        public bool IsHidden { get; set; }

        public List<QuestionOptionViewModel> Options { get; set; }
    }

1 个答案:

答案 0 :(得分:2)

您需要Select

之类的内容
Questions = surveyData.Questions.Select(q => new QuestionViewModel
    {
        Id = q.Id,
        QuestionType = q.QuestionType,
        ...
        Options = Options
    }).ToList()

请确保您拥有using System.Linq;。如果您经常使用这种映射任务,也可以考虑像Automapper这样的工具。