Kavitha P.
Kavitha P.

Reputation: 155

How to add a collection of list into a list?

I have my code like,

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

I cannot add a list into another list.Kindly tell me what to do in this case.

Upvotes: 1

Views: 119

Answers (4)

Gerald Versluis
Gerald Versluis

Reputation: 33993

Look at the Concat function within the System.Linq namespace

I.e.

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

But why not at the place of; list.Add(answerSetContract.AnswerText); add it directly to model.QuestionSetList?

So like this;

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

Upvotes: 2

Davide Lettieri
Davide Lettieri

Reputation: 326

You should try with AddRange, it allows to add a collection to a List

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

Upvotes: 1

Daryl
Daryl

Reputation: 610

model.QuestionSetList is a list of strings. You're trying to add a list of strings to it. As their types are incompatible, it won't allow you to do that.

Try making model.QuestionSetList a List<List<string>> and see if that helps you.

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

If you want a List of Lists, then your QuestionSetList would have to be:

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

Consider creating a custom type though, otherwise it's a bit like inception, list in a list in a list in a list.........

Or if you're actually wanting to combine the Lists, then use Concat:

list1.Concat(list2);

Upvotes: 2

Related Questions