score:3

Accepted answer

You're modifying a variable within a query:

long l_nAccumulatedCmdLength = 0;
IEnumerable<FileInfo> l_selectedFiles = l_allFiles
     .TakeWhile(l_fileInfo => (l_nAccumulatedCmdLength += l_fileInfo.Length) <=
                                   Settings.Default.Threshold);

Note the change to l_nAccumulatedCmdLength within your TakeWhile condition.

That's a really bad idea, which will end up with the sequence giving different results each time you evaluate it. Just don't do it. I strongly suspect that's the cause of the problem.

Note that this part:

To add to the mistery, the debugger always updates the value of l_nAccumulatedLength not after execution of the TakeWhile() method, but after executing the next l_selectedFiles.Count() statement.

... is very easily explained. TakeWhile doesn't iterate over the sequence - it just builds a new sequence which will be lazily evaluated.

If you want to get consistent results, use ToList... but it would be much better not to modify a variable in the query in the first place. Use Aggregate to create a sequence of Tuple<FileInfo, long> values where the long value is the "size so far" if you want.


Related Query

More Query from same tag