簡體   English   中英

如何轉換System.Linq.Enumerable.WhereListIterator <int> 列表 <int> ?

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

在下面的示例中,如何輕松地將eventScores轉換為List<int>以便我可以將其用作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();

不起作用?

順便說一下,為什么你為score參數聲明具有這種特定類型的prettyPrint,而不是僅將此參數用作IEnumerable(我假設這是你實現ForEach擴展方法的方式)? 那么為什么不改變prettyPrint簽名並保持這個懶惰的評估呢? =)

像這樣:

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

更新:

或者你可以避免像這樣使用List.ForEach(不考慮字符串連接效率低下):

var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM