Skip to main content
 首页 » 编程设计

c#之如何将列表集合添加到列表中

2024年02月01日31xing901022

我有我的代码,

List<string> list = new List<string>(); 
model.QuestionSetList = new  List<string>(); 
for (int i = 0; i < response.QuestionsInfoList.Count(); i++) 
{ 
     list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question); 
     foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList) 
     { 
         list.Add(answerSetContract.AnswerText); 
     } 
     model.QuestionSetList.Add(list) 
} 

我无法将一个列表添加到另一个列表中。请告诉我在这种情况下该怎么做。

请您参考如下方法:

查看 System.Linq 命名空间中的 Concat 函数

即

using System.Linq; 
 
List<string> list = new List<string>(); 
model.QuestionSetList = new  List<string>(); 
for (int i = 0; i < response.QuestionsInfoList.Count(); i++) 
{ 
     list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question); 
     foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList) 
     { 
         list.Add(answerSetContract.AnswerText); 
     } 
     model.QuestionSetList = model.QuestionSetList.Concat(list); 
} 

但为什么不在; list.Add(answerSetContract.AnswerText);直接添加到model.QuestionSetList?

像这样;

List<string> list = new List<string>(); 
model.QuestionSetList = new  List<string>(); 
for (int i = 0; i < response.QuestionsInfoList.Count(); i++) 
{ 
     list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question); 
     foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList) 
     { 
         model.QuestionSetList.Add(answerSetContract.AnswerText); 
     } 
}