Home > OS >  Reading text data from tab delimited file without headers in C#
Reading text data from tab delimited file without headers in C#

Time:01-02

I want to read text data from a .txt file in which the data is tab separated. I am pasting the sample data below. [1]: https://i.stack.imgur.com/t9cPt.png

Now what I want is to read the data into one single List of type string without headers.

I currently have the following code:

            
            var sepList = new List<string>();

            // Read the file and display it line by line.
            using (var file = new StreamReader(docPath))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    var delimiters = '\t';
                    var segments = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var segment in segments)
                    {
                        //Console.WriteLine(segment);
                        sepList.Add(segment);
                    }   
                }
            }

Any help will be greatly appreciated :)[![enter image description here][1]][1]

CodePudding user response:

I want is to read the data into one single List of type string without headers.

Add file.ReadLine(); before reading the file it will skip the header or first line of the file.

Try this:-

var sepList = new List<string>();


using (var file = new StreamReader(docPath))
{
    // Skip the first line (the header)
    file.ReadLine();

    string line;
    while ((line = file.ReadLine()) != null)
    {
        var delimiters = '\t';
        var segments = line.Split(
           delimiters, StringSplitOptions.RemoveEmptyEntries
        );

        foreach (var segment in segments)
        {
            // console.WriteLine(segment);
            sepList.Add(segment);
        }   
    }
}

CodePudding user response:

You can get your result with a single line.

var data = File.ReadLines(docPath)
               .Skip(1)
               .Select(x => x.Split(new char[] {'\t'},StringSplitOptions.RemoveEmptyEntries))
               .SelectMany(k => k);

First, we use File.ReadLines that enumerates the lines from the file creating a sequence that we can feed to the following commands. Then we Skip the first line from the sequence and on the remaining items we apply the Split operation getting another sequence of two or more values that we can add as single items to the IEnumerable assigned to the data variable. Of course a ToList will materialize the IEnumerable into the final processing data.

  • Related