tags:

views:

898

answers:

3

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); }
+8  A: 
var evenScores = scores.Where(i => i % 2 == 0).ToList();

Doesn't work?

Justin Niessner
+11  A: 

You'd use the ToList extension:

var evenScores = scores.Where(i => i % 2 == 0).ToList();
Pete OHanlon
leppie
Pfft, micro-optimizations not driven by profiling. The creation of the iterator and the copy to the list are going to be hundreds of times slower than any savings made by micro-optimizing the math. *Optimize the slow stuff.*
Eric Lippert
+1  A: 

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);
Dzmitry Huba
Maybe because `ForEach` is a built-in method on the `List<T>` class. You'd have to write your own extension method to use `ForEach` with `IEnumerable<T>`.
LukeH