I am trying to read in a file, which is essentially a list of integers separated by a line. Obviously, file input can never be trusted, so I need to filter out non-integer numbers.
I know that the as operator usually converts if it can, and then sets it to null, however, since int not null, it is not. I thought that maybe I could pounce on the Nullable<int> . I never delved into this, I thought that maybe I could do:
var lines = File.ReadAllLines(""); var numbers = lines.Select(line => line as int?).Where(i => i != null);
I know that I could potentially get around this by doing:
var numbers = lines.Select(line => { int iReturn = 0; if (int.TryParse(line, out iReturn )) return iReturn; else return null; }).Where(i => i != null);
I could also do this as an extension method.
I was just looking for a neat, concise way to make the cast in a statement, and also to understand why my code is invalid.
source share