Remove row from an array

Asked

Viewed 807 times

1

How do I remove the line without getting blank?

N7 G90
N8 G26 RA 10.840
N9 G54 G92 X115.00 Y25.00

N11 C5
N12 D14
N13 G42 G01 X76.3276 Y-19.86 

Having to stay that way:

N7 G90
N8 G26 RA 10.840
N9 G54 G92 X115.00 Y25.00
N11 C5
N12 D14
N13 G42 G01 X76.3276 Y-19.86 

My code for now is like this:

//Remove Line Condition
if (_OS.Contains("M31"))
{
    _OS = _OS.Remove(0);
}
  • That would be a file you carry,?

  • exact.. Virgilio, I charge it, manipulate it into an array!

3 answers

1

Could use System.IO.File.ReadAllLines to read all lines of the file and delete those that are blank with Linq ([Where](c => !string.IsNullOrEmpty(c))):

string[] arquivo = System.IO.File.ReadAllLines("arquivo.txt")
                .Where(c => !string.IsNullOrEmpty(c)).ToArray();

System.IO.File.WriteAllLines("arquivo.txt", arquivo);

If you want to create the file, do it with System.IO.File.WriteAllLines, in this example, the file has been rewritten. You can easily choose another name and keep the original and the change.

1

You can use a lambda expression to do that

strArray = strArray.Where( x=>!x.Contains("M31")).ToArray();

He’s gonna get his array, see which of the items does not contain the string "M31" and mount a new array with the output, removing any empty key.

1


An alternative, besides the option posted by Virgilio, if you are dealing with a heavy file, is to read the file line by line, in this process you can skip lines that do not satisfy a certain condition, for example, use String.IsNullOrEmpty to check if the line is empty:

using System.Collections.Generic;
using System.IO;
//....

public static void Main(string[] args)
{
    List<string> linhas = new List<string>();

    using (StreamReader sr = new StreamReader("foo.txt"))
    {
        string linha;
        while ((linha = sr.ReadLine()) != null)
        {
            if (string.IsNullOrEmpty(linha)) // Aqui você pode incluir mais condições com ||
            {
                continue;
            }
            linhas.Add(linha);
        }
    }

    // Use "linhas" aqui...
}

A second alternative, if you are using lists, is the method List<T>.RemoveAll:

List<string> linhas = new List<string>();
// Inserindo valores na lista...

linhas.RemoveAll(linha => string.IsNullOrEmpty(linha));
  • I tried all the ways. and yours worked out here, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.