2015-02-05 103 views
-3

現在我只得到1個questionID,我怎麼能得到所有相關的問題id foreach項目?嵌套ForEach列表

我希望該項目以類似這樣的輸出: 項目 - 文本= 「itemTitle」 值= 「questionID1,questionID2,questionID3等」

感謝答案

 string categoryId = ""; 
     string questionID = ""; 


     foreach (var item in searchList.resources) 
     { 
       foreach (var associatedQuestion in item.associatedQuestions) 
       { 
        categoryId = associatedQuestion.categoryid.ToString(); 

        questionID = associatedQuestion.id.ToString(); 

       } 

       myList.Add(new SelectListItem { Text = item.linktext.ToString(), Value = categoryId + questionID }); 

     } 

     return System.Web.Helpers.Json.Encode(myList); 
    } 
+1

什麼是searchList的價值,associatedQuestion等你的問題和代碼示例是模糊 – jrarama 2015-02-05 14:50:19

+1

重新分配'categoryId'和'questionId'在foreach所以只有最後一個被使用的每一次迭代 - 移動'myList.Add'最多3行 – Sayse 2015-02-05 14:51:27

+0

嘗試對myList(而不是列表)使用字典>。這會給你所有的標題不同的值。 – AWinkle 2015-02-05 14:52:13

回答

1

例如,您可以將String.Join與LINQ結合使用,而不是內部的foreach循環。例如:

foreach (var item in searchList.resources) 
{ 
     //First convert all questionIds to a string collection 
     IEnumerable<String> allQuestionIDs = item.associatedQuestions.Select(q => q.id.ToString()); 

     //Convert the collection to single comma seperated String 
     string questionIdsString = String.Join(", ", allQuestionIDs); 

     myList.Add(new SelectListItem { Text = item.linktext.ToString(), Value = questionIdsString }); 
} 
+0

謝謝你,工作 – Peter 2015-02-05 15:16:39