Home > Blockchain >  split data into two column in a csv using C#
split data into two column in a csv using C#

Time:11-08

I want to split table data into two column in CSV. I have a table with one column(eg. pincode) having 100 records. using c# I have created the csv file but I want to split this record into two column (eg, pincode1, pincode2).

Can anybody suggest that how can we achieve this?

Thanks in advance

here is the code

var pincodes= DataSourceAccess.RetrieveLockedTns(Convert.ToInt32(count));
if (pincodes?.Count() > 0)
{
     var csv = new StringBuilder();
     pincodes.ForEach(x => csv.AppendLine(x));
     File.WriteAllText(path, csv.ToString());
}

lets consider there are 10 records I am getting from database the data it is producing is a csv file with pincodes

 12345  
 23455  
 34543  
 22345
 24554  
 23857 
 57485  
 94859  
 93846  
 47395

the result I want first 5 records in one column(pincode1) and other 5 records in other column(pincode2)

pincode1 pincode2
12345     23857
23455     57485
34543     94859
22345     93846
24554     47395

CodePudding user response:

I think a simple for loop will solve this one best, rather than foreach

int half = pincodes.Count/2;
for(int x = 0; x < half; x  )
    csv.Append(pin[x]).Append('\t').AppendLine(pin[x half]);

CodePudding user response:

You can use a for loop to create two string builders, one for each half then write the string to a csv file. The code below is tested and it works. I have also attached images of the csv files created.

using System.IO;
using System.Text;

            int[] pincodes = new int[] {1123, 677,098,666 };
            int pinCount = pincodes.Length;
            int pinHalf = 0;
            StringBuilder sbOut1 = new StringBuilder();
            StringBuilder sbOut2 = new StringBuilder();
            
            if (pinCount>1)
                pinHalf = pinCount / 2;
            for (int i = 0; i < pinHalf; i  )
            {
                sbOut1.AppendLine(string.Join(",", pincodes[i].ToString()));
            };
            for (int i = pinHalf; i < pinCount; i  )
            {
                sbOut2.AppendLine(string.Join(",", pincodes[i].ToString()));
            };

            string path1 = AppContext.BaseDirectory   "mypins.csv";
            string path2 = AppContext.BaseDirectory   "mypins2.csv";
            
            File.WriteAllText(path1, sbOut1.ToString());
            File.WriteAllText(path2, sbOut2.ToString());

Image of first csv created

Image of second cvs created

  • Related