如何将列表集合添加到列表中?

How to add a collection of list into a list?

我有我的代码,

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)
}

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

如果您想要 ListList,那么您的 QuestionSetList 必须是:

model.QuestionSetList = new List<List<<string>>()

尽管考虑创建自定义类型,否则有点像inception,list in a list in a list in a list......

或者如果你真的想合并Lists,那么使用Concat:

list1.Concat(list2);

查看 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);
     }
}

model.QuestionSetList 是一个字符串列表。 您正在尝试向其中添加一个字符串列表。由于它们的类型不兼容,因此不允许您这样做。

尝试将 model.QuestionSetList 设为 List<List<string>>,看看是否对您有帮助。

您应该尝试使用 AddRange,它允许将集合添加到列表

http://msdn.microsoft.com/en-us/library/z883w3dc.aspx