2014-02-13 178 views
0

我有兩種不同的型號。一個是視圖模型,另一個是標準模型。我試圖將一個模型的結果合併到第二個視圖模型中。我被困在循環部分。將一個列表從一個模型合併到另一個模型中?

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; } 
    } 
+2

什麼問題? –

回答

2

看起來你需要像Select

Questions = surveyData.Questions.Select(q => new QuestionViewModel 
    { 
     Id = q.Id, 
     QuestionType = q.QuestionType, 
     ... 
     Options = Options 
    }).ToList() 

請確保您有using System.Linq;這一點。你也可以考慮像Automapper這樣的工具,如果這樣的映射任務對你來說很頻繁。

+0

完美工作 – allencoded

相關問題