File to Integer Array

2

Currently I have a txt file where there are many lines, each of these lines can be a string, an integer, a line break, etc ... The fact is that I'm looking for a clean way to load lines that are integers in a list of integers.

Doing it by means of loops and comparisons is not a 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 not find a way to filter from Split

I would also not care if the result was stored in an array of integers.

Edit: Doing it "in the rough", 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)
                    { }
                }
            }
    
asked by U. Busto 11.09.2017 в 09:19
source

2 answers

2

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 paired to int with a Where using int.TryParse . Later you make a Select of these lines using int.Parse . Finally,% is used ToList<int> . I'll give you an example:

int entero;
string[] prueba = new string[] { "1", "a", "b", "5" };
var lista1 = prueba.Where(x => int.TryParse(x, out entero))
                   .Select(x=>int.Parse(x))
                   .ToList<int>();

In your case, you should have the following:

int entero;
var lista=streamReader.ReadToEnd().Split(' ')
                       .Where(x => int.TryParse(x, out entero))
                       .Select(x=>int.Parse(x))
                       .ToList<int>();
    
answered by 11.09.2017 / 09:46
source
3

Pikoh's response is fine however there is no need to do twice the Parse or TryParse :

Query syntax

int entero = 0;
var lista = from x in streamReader.ReadToEnd().Split(' ')
            where Int32.TryParse(x, out entero)
            select entero;

Method syntax

int entero = 0;
var lista = streamReader.ReadToEnd().Split(' ')
    .Where(x => int.TryParse(x, out entero))
    .Select(x => entero);
    
answered by 11.09.2017 в 09:57