Question

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); }
Was it helpful?

Solution

You'd use the ToList extension:

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

OTHER TIPS

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

Doesn't work?

By the way why do you declare prettyPrint with such specific type for scores parameter and than use this parameter only as IEnumerable (I assume this is how you implemented ForEach extension method)? So why not change prettyPrint signature and keep this lazy evaluated? =)

Like this:

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

prettyPrint(scores.Where(i => i % 2 == 0), "Title");

Update:

Or you can avoid using List.ForEach like this (do not take into account string concatenation inefficiency):

var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top