2015-11-19 73 views
0

我有一個ControlMeasure表,其中包含每個控制度量和一個ControlMeasurepeopleExposed表,其中包含控制度量中公開的每個人的記錄,這可能是1條記錄或多條記錄。IEnumerable內的StringBuilder

我有填充一個列表視圖

對於列表中的每個項目的控制,控制措施,我想創建一個字符串,顯示所有的高危人羣

例如

PeopleString = "Employees, Public, Others"; 

伊夫添加一個foreach控制器,以顯示我想要做但是我知道,這不會工作。

控制器是這樣的:

 public ActionResult ControlMeasureList(int raId) 
    { 
     //Populate the list 
     var hazards = new List<Hazard>(db.Hazards); 
     var controlMeasures = new List<ControlMeasure>(db.ControlMeasures).Where(x => x.RiskAssessmentId == raId); 

     var cmcombined = (
           from g in hazards 
           join f in controlMeasures 
           on new { g.HazardId } equals new { f.HazardId } 
           select new CMCombined 
           { 
            Activity = f.Activity, 
            ControlMeasureId = f.ControlMeasureId, 
            ExistingMeasure = f.ExistingMeasure, 
            HazardName = g.Name, 
            LikelihoodId = f.LikelihoodId, 
            Rating = f.Rating, 
            RiskAssessmentId = f.RiskAssessmentId, 
            SeverityId = f.SeverityId, 
            }).OrderBy(x => x.Activity).ToList(); 

     var cmPeopleExp = new List<ControlMeasurePeopleExposed>(db.ControlMeasurePeopleExposeds).Where(x => x.RiskAssessmentId == raId); 
     var peopleExp = from c in cmPeopleExp 
         join d in db.PeopleExposeds 
         on c.PeopleExposedId equals d.PeopleExposedId 
         orderby d.Name 
         select new RAPeopleExp 
         { 
          RAPeopleExpId = c.PeopleExposedId, 
          PeopleExpId = c.PeopleExposedId, 
          PeopleExpName = d.Name, 
          RiskAssessmentId = c.RiskAssessmentId, 
          ControlMeasureId = c.ControlMeasureId 
         }; 

     var model = cmcombined.Select(t => new FullControlMeasureListViewModel 
     { 
      ControlMeasureId = t.ControlMeasureId, 
      HazardName = t.HazardName, 
      LikelihoodId = t.LikelihoodId, 
      Rating = t.Rating, 
      SeverityId = t.SeverityId, 
      Activity = t.Activity, 
      ExCM = t.ExistingMeasure, 
      //This section here is where I'm struggling 
      var PeopleString = new StringBuilder(); 
      foreach (var p in peopleExp) 
      { 
       PeopleString.AppendLine(p.PeopleName); 
      { 
      PeopleExposed = PeopleString, 
     }); 
     return PartialView("_ControlMeasureList", model); 
    } 

我知道我不能直接把這個代碼的控制器,但它確實代表了我想做的事情。

+2

您是否嘗試過使用的string.join?它有兩個參數:你需要連接的字符串列表和分隔符(逗號,在你的情況下) –

+0

我修改了帖子以顯示我以後的內容,抱歉這是一個複製和粘貼錯誤,這意味着所有的帖子都不是所示。 –

回答

2

您不能在對象初始值設定項中使用foreach(這是您在實例化FullControlMeasureListViewModel時要做的事)。你可以,但是,使用的string.JoinpeopleExp.Select組合:

var model = cmcombined.Select(t => new FullControlMeasureListViewModel 
    { 
     //other props 
     PeopleExposed = string.Join(",", peopleExp 
            .Where(p => p.ControlMeasureId == t.ControlMeasureId) 
            .Select(p => p.PeopleExpName)); 
     //other props 
    }); 
+0

感謝@DaveZych一個不錯的簡單解決方案 –