How to convert System.Linq.Enumerable.WhereListIterator<int> to List<int>?

Edward Tanguay picture Edward Tanguay · Oct 8, 2009 · Viewed 34.3k times · Source

In the below example, how can I easily convert eventScores to List<int> so that I can use it as a parameter for prettyPrint?

Console.WriteLine("Example of LINQ's Where:");
List<int> scores = new List<int> { 1,2,3,4,5,6,7,8 };
var evenScores = scores.Where(i => i % 2 == 0);

Action<List<int>, string> prettyPrint = (list, title) =>
    {
        Console.WriteLine("*** {0} ***", title);
        list.ForEach(i => Console.WriteLine(i));
    };

scores.ForEach(i => Console.WriteLine(i));
prettyPrint(scores, "The Scores:");
foreach (int score in evenScores) { Console.WriteLine(score); }

Answer

Pete OHanlon picture Pete OHanlon · Oct 8, 2009

You'd use the ToList extension:

var evenScores = scores.Where(i => i % 2 == 0).ToList();