简体   繁体   English

Linq表达式和foreach产生不同的结果

[英]Linq expression and foreach produce different results

Could you please explain why the output of those two functions is different for the same data? 你能否解释为什么这两个函数的输出对于相同的数据是不同的?
I expected them to produce the same output ie append lines. 我希望它们产生相同的输出,即追加线。 How can I change alternative 1 to add lines? 如何更改备选1以添加行?

(Background Measurements implements ICollection<> ) (背景Measurements实现ICollection<>

Alternative 1 备选方案1

private void CreateBody(TestRun testRun, StringBuilder lines)
{
    testRun.Measurements.OrderBy(m => m.TimeStamp)
       .Select(m => lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc)));
}

-> no output/added lines - >没有输出/添加行

Alternative 2 备选方案2

private void CreateBody2(TestRun testRun, StringBuilder lines)
{
    foreach (Measurement m in testRun.Measurements.OrderBy(m => m.TimeStamp))
    {
        lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc));
    }
}

-> added lines for each measurement - >为每次测量添加行

Because linq delays execution therefore doing the select will never happen (since you're doing the select and then exiting the method), whereas the foreach will do the execution right at the time you execute your method. 因为linq会延迟执行,因此执行select将永远不会发生(因为你正在执行select然后退出方法),而foreach将在你执行方法时立即执行。 You need to enumerate the result you're selecting. 您需要枚举您选择的结果。 For example by doing a ToList() or a ToArray() to force the method to enumerate, or you could take a different approach altogether. 例如,通过执行ToList()或ToArray()来强制方法枚举,或者您可以完全采用不同的方法。

private void CreateBody(TestRun testRun, StringBuilder lines)
{
    testRun.Measurements.OrderBy(m => m.TimeStamp).ToList().ForEach(m => lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc)));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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