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 i.e. append lines. How can I change alternative 1 to add lines?
(Background Measurements
implements ICollection<>
)
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
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. 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.
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)));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With