现在我只得到1个问题ID,我怎样才能获得所有关联的问题id foreach item?
我希望项目输出如下: Item - Text =“itemTitle” Value =“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);
}
答案 0 :(得分: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 });
}