I think the best way to explain my question is with a short (generic) linq-to-objects code sample:
IEnumerable<string> ReadLines(string filename)
{
string line;
using (var rdr = new StreamReader(filename))
while ( (line = rdr.ReadLine()) != null)
yield return line;
}
IEnumerable<int> XValuesFromFile(string filename)
{
return ReadLines(filename)
.Select(l => l.Substring(3,3))
.Where(l => int.TryParse(l))
.Select(i => int.Parse(i));
}
Notice that this code parses the integer twice. I know I’m missing an obvious simple way to eliminate one of those calls safely (namely because I’ve done it before). I just can’t find it right now. How can I do this?
I think I’ll go with something like this:
I don’t really like this, though, as I’m already on the record as not liking using tuples in this way. Unfortunately, I don’t see many alternatives outside of abusing exceptions or restricting it to reference types (where
nullis defined as a failed conversion), neither of which is much better.