IEnumerable Any() and First() - Fun C# Code 5

I ran into an interesting problem today. Using CsvHelper, I was getting a list of records from a file, then check if there are any records to process. If not then skip processing of that file, otherwise, pick the first record and do something with the data.

I've added a couple of unit tests to catch issues and all was well. Deployed the code to production and it blew up: "System.InvalidOperationException: Sequence contains no elements". The issue happened for one file only. It so happened, that the file contained only one record. It is super-obvious when you see it.

The IEnumerable had a deffered execution. Any() would take the first item from IEnumerable to check if there are any values, but it would not reset the underlying collection. The documentation states: "The enumeration of source is stopped as soon as the result can be determined.", but doesn't mention anything about a reset. The simplest way to solve the issue is to execute IEnumerable before making any calls by adding .ToList() or similar.

Leave a comment