What about:
int? TryParse(string s) { int i; return int.TryParse(s, out i) ? (int?)i : (int?)null; } IEnumerable<int> XValuesFromFile(string filename) { return from line in ReadLines(filename) let start = line.Substring(3,3) let parsed = TryParse(start) where parsed != null select parsed.GetValueOrDefault(); }
Perhaps you could combine the second / third lines if you want:
return from line in ReadLines(filename) let parsed = TryParse(line.Substring(3,3))
The choice of GetValueOrDefault is that it skips the validation check performed by the (int) or .Value command, that is, it (ever a little) is faster (and we already checked that it is not null ).
source share