I like LINQ instructions for expressive syntax and other convenient functions. However, it is very difficult for me to debug them sometimes. In particular, when I run the LINQ statement in the collection and one of the elements in the collection throws an exception, how can I find out what the problem is and where the problem came from?
Suppose I have a text file with 1000 real numbers:
0.46578 12.314213 1.444876 ...
I read this as a List<string> and load it into a more specific data structure:
var file_contents = File.ReadAllLines("myfile.txt"); var data = file_contents.Select(s => double.Parse(s));
Now, for this particular input, I did not look at it carefully, and it turns out that the 876th line contains (line numbers shown):
875 5.56786450 876 Error: Could not calculate value. 878 0.0316213
For some reason (maybe the file was generated using a script that worked). My LINQ method chain will, of course, throw an exception. The problem is, how can I determine which list item raised an exception, and what is its meaning?
To clarify if I used the for loop instead:
var data = new List<double>(); foreach(var row in file_contents) { var d = double.Parse(row); data.Add(d); }
Then the exception will double.Parse line that calls double.Parse , and I could hover over row to easily see what the problem is.
I can of course use Resharper to convert my LINQ statements to for-loops and then debug them, but is there a better way?