Thomas
Thomas

Reputation: 5921

Using Linq to merge all List returned by the method of an object in a List

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

Answers (2)

Bob Vale
Bob Vale

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

Ilya Ivanov
Ilya Ivanov

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

Related Questions