简体   繁体   中英

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

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); }

您将使用ToList扩展名:

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

不起作用?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM