Removing alternative lines from a text file using C #

I am doing a project where I have to read data from a .txt file and then insert each row into a table using a query.

Now, for example, the contents of the text file will be

11111

1111x

22222

2222x

33333

3333x

etc.

Now that you see that the alternate row is almost repeating, so I would like to remove the alternate rows so that the available data becomes

11111

22222

33333

and then process the rest of my codes.

Is there any way to do this?

So far I have used a list of arrays to get this

using (StreamReader sr = new StreamReader(Server.MapPath("03122013114450.txt"), true))
        {

            string txtValues = sr.ReadToEnd();
            string[] txtValuesArray1 = Regex.Split(txtValues, "\r\n");



            ArrayList array = new ArrayList();
            foreach (string value in txtValuesArray1)
            {
                array.Add(value);
            }

            for (int i = 0; i < array.Count; i++)
            {
                if (array.Count % 2 != 0)
                    array.RemoveAt(i + 2);
                else
                    array.RemoveAt(i + 1);
            }
        }

The main idea is to remove the alternative lines so that they are from the arraylist index from the text file.

+5
source share
4 answers

Another optimization:

using (var sr = new StreamReader(Server.MapPath("03122013114450.txt"), true))
{
    var line = sr.ReadLine();
    while (line != null)
    {
        // Do stuff here. Add to the list, maybe?

        if (sr.ReadLine()!= null) //read the next line and ignore it.
            line = sr.ReadLine();
    }
}

, line = sr.ReadLine(); while

+1

,

static IEnumerable<string> OddLines(string path)
{
    var flipper = true;

    foreach (var line in File.ReadLines(path))
    {
        if (flipper) yield return line;
        flipper = !flipper;
    }
}

, ,

var oddlines = OddLines(Server.MapPath("03122013114450.txt")); 

var oddlines = File.ReadLines(Server.MapPath("03122013114450.txt"))
                   .Where((l, i) => i % 2 == 0);
+1

LINQ

string[] lines = File.ReadAllLines("your_file_name");
var result = lines.Where((s, idx) => idx % 2 == 0);

Of course, if your file is very large, you need to work on a line and skip unnecessary lines when reading

+1
source

What you usually want to do is read one line of the file at a time, rather than buffering all the data on disk to memory. Think about whether it was a 2GB text file (not such an unusual problem) - you expect 2GBs to load first before you start processing it.

ulong count = 0;
using (StreamReader sr = new StreamReader(Server.MapPath("03122013114450.txt"), true))
{
   while (!sr.EndOfStream) {
       count++;
       String line = sr.ReadLine();
       if ((count % 2) == 0) {
           // do additional processing here
           // like insert row into database
       }
    }
}

(My C # is rusty.)

0
source

All Articles