I currently have a txt file where there are a multitude of lines, each of these lines can be a string, an integer, a newline, etc... The fact is that I am looking for a clean way to load in a list of integers those lines that are integers.
Doing it through loops and comparisons is no problem but I would like to do it using Linq.
I am currently at this point:
List<int> lista = new List<int>();
lista = streamReader.ReadToEnd().Split(' ').;
I can't find the way to filter from Split
I also wouldn't mind if the result was stored in an array of integers.
Edit: Doing it "roughly", with loops and others works for me, it would look like this:
List<int> lista = new List<int>();
List<string> temp = new List<string>();
temp = streamReader.ReadToEnd().Split(' ').ToList();
for (int i = 0; i< temp.Count; i++)
{
if (temp[i].Length > 0)
{
int x = int.MinValue;
try
{
x = int.Parse(temp[i]);
if (x > int.MinValue)
lista.Add(x);
}
catch(Exception ex)
{ }
}
}
Pikoh's answer is fine however there is no need to do the
Parse
or twiceTryParse
:query syntax
Method Syntax
There are several ways to do what you want, I show you one below.
What you must do is first select the lines that can be parsed
int
with aWhere
using . Laterint.TryParse
oneSelect
of these lines is made usingint.Parse
. Finally, useToList<int>
. I give you an example:In your case, you should have the following: