如何将System.Linq.Enumerable.WhereListIterator <int>转换为List <int>?

Edw*_*uay 12 c# linq action func

在下面的例子中,我如何轻松转换eventScoresList<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); }
Run Code Online (Sandbox Code Playgroud)

Pet*_*lon 23

您将使用ToList扩展名:

var evenScores = scores.Where(i => i % 2 == 0).ToList();
Run Code Online (Sandbox Code Playgroud)

  • Pfft,微观优化不是由分析驱动的.迭代器的创建和列表的复制将比微优化数学所节省的成本慢几百倍.*优化缓慢的东西.* (26认同)
  • @FoggyDay:我们可以根据我的反应重建被删除评论的内容。可能有人建议将“i % 2 == 0”替换为“i &amp; 0x1 == 0”。现在,在 x86 上实现 mod 的 DIV 指令确实比 AND 引入了几纳秒的 CPU 延迟。但抖动的作者们都知道这个事实!为了取得性能上的胜利,我们需要知道(1)抖动效果不好,(2)节省纳秒延迟是程序中最慢的事情,(3)程序慢得令人无法接受已经。 (2认同)

Jus*_*ner 9

var evenScores = scores.Where(i => i % 2 == 0).ToList();
Run Code Online (Sandbox Code Playgroud)

不起作用?