Reputation: 5921
So this is my test case :
I have a class QuizzResult that hold all the answer choosen by a user:
public class QuizzResult
{
public List<int> Answers { get; set; }
}
When the test is finished, I have a list of results:
List<QuizzResult> allResult
So I just want to have the list (with duplicates) of all the merged answers of all QuizzResults.
I tried to look around Select, but I have a IEnumerable>. I fell I should use ForEach, but I don't know how...
Any hint?
Upvotes: 2
Views: 95
Reputation: 18474
As my comment was the required answer, converting to an answer.
When you wish to combine a collection of collections into a single collection you can use the
SelectMany
(MSDN) method
allResult.SelectMany(x => x.Answers)
This will use defered execution so if you wish to evaluate this immediately, tag a ToList
or ToArray
call on the end. As you are using Lists, here is an example with ToList
List<int> allAnswers = allResult.SelectMany(x => x.Answers).ToList();
Upvotes: 1
Reputation: 23646
SelectMany
will flatten your list of lists into one single enumerable of answers:
IEnumerable<int> allAnswers = allResult.SelectMany(quizz => quizz.Answers);
To get List<int>
use ToList
extension method, which will eagerly read all the items and create a List
List<int> allAnswers = allResult.SelectMany(quizz => quizz.Answers)
.ToList();
Upvotes: 10