For programmers who do not come from the functional background of programming, are there any errors that should be avoided?
Good question. As Judah points out, the biggest thing is that the query expression builds the query; it does not execute the query that it creates.
The immediate consequence of this fact is that you execute the same query twice to return different results.
The immediate consequence of this fact is that the query is executed for the second time, not reusing the results of the previous execution, as new results may differ.
Another important fact is that queries are best to ask questions, rather than change state. Try to avoid any queries that directly or indirectly force something to change its meaning. For example, many people try to do something like:
int number; from s in strings let b = Int32.TryParse(s, out number) blah blah blah
It just asks for a world of pain, because TryParse mutates the value of a variable that is outside the query.
In this particular case, you better do
int? MyParse(string s) { int result; return Int32.TryParse(s, out result) ? (int?)result : (int?)null; } ... from s in strings let number = MyParse(s) where number != null blah blah blah...
Eric Lippert
source share