4est
4est

Reputation: 3168

Transpose CSV to new format (C#)

I have csv file:

enter image description here

I need to convert it to below format:

enter image description here

I did only this:

    StreamReader srd = new StreamReader(path: path);
    int rowCount = 0;

    string[] oStreamDataValues = null;
    string[] headerNames = null;

    while (!srd.EndOfStream)
    {
        string oStreamRowData = srd.ReadLine().Trim(); 
        oStreamDataValues = oStreamRowData.Split(';');

        //headers 
        if (rowCount == 0)
        {
            headerNames = oStreamDataValues;
            rowCount++;//second row go to "else"                      
        }
        //create new csv
        else
        {

        }            
        //rowCount++;
    }
    //Console.WriteLine("number of lines " + rowCount);
    srd.Dispose();

Can you please help me with transpose to new format?

Upvotes: 1

Views: 246

Answers (2)

torsan
torsan

Reputation: 489

You can try this for you else clause:

            else
            {
                string leftColumn = oStreamDataValues[0];

                for (int i = 1; i < oStreamDataValues.Length; i++)
                {
                    string middleColumn = headerNames[i];
                    string rightColumn = oStreamDataValues[i];
                    string newRow = string.Join(";", leftColumn, middleColumn, rightColumn, Environment.NewLine);

                    File.AppendAllText(pathToNewFile, newRow);
                }
            }

EDIT: or use Linq:

var result = headerNames.Skip(1).Zip(oStreamDataValues.Skip(1), (a, b) => String.Join(";", oStreamDataValues[0], a, b));

Upvotes: 1

skyoxZ
skyoxZ

Reputation: 462

using System;
using System.IO;

namespace SharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "XXX/test.csv";
            string savePath = "XXX/test2.txt";          
            using(StreamReader sr = new StreamReader(path))
            {
                string headerLine = sr.ReadLine();
                string[] headers = headerLine.Split(';');
                using(StreamWriter sw = new StreamWriter(savePath))
                {
                    while (true)
                    {
                        string line = sr.ReadLine();
                        if (line == null) return;
                        string[] ss = line.Split(';');
                        if (ss.Length != headers.Length) continue;
                        for (int i = 1; i < headers.Length; i++)
                        {
                            sw.WriteLine(ss[0] + ";" + headers[i] + ";" + ss[i]);
                        }
                    }
                }
            }
        }
    }
}

Test CSV:

ID;Col2;Col3;Col4
id1;10;def;20
Id2;30;aaa;40

Upvotes: 0

Related Questions