Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq expression and foreach produce different results

Tags:

c#

linq

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

Alternative 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

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

like image 578
nabulke Avatar asked Aug 14 '13 11:08

nabulke


1 Answers

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)));
}
like image 137
nerdybeardo Avatar answered Nov 15 '22 06:11

nerdybeardo