Reputation: 255
Is it possible to use for loop inside the add method? This is my code and i want to add to each question four answers :
for (int i = 0; i < 40; i++)
{
Questions.Add(new Question
{
QuestionString = GlobalClass.RandomString(40),
Answers = new List<Answer>() {
for(int j = 0; j<4; j++){
new Answer { } ...
}
}
});
}
something like this. I know there are other ways, but just intrested in if it's possible
Upvotes: 0
Views: 151
Reputation: 791
It is possible, for example you can use mentioned Enumerable.Range
new List<Answer>(Enumerable.Range(0, 4).Select(i => new Answer { ... }));
but please don't use such constructions, it is very hard to debug.
Upvotes: 0
Reputation: 2267
You can use Enumerable.Range
for (int i = 0; i < 40; i++)
{
Questions.Add(new Question
{
QuestionString = GlobalClass.RandomString(40),
Answers = Enumerable.Range( 0,4 ).Select( x=>new Answer {
Id = x
}).ToList()
});
}
Upvotes: 3