Search code examples
c#csvdatatable

split data into two column in a csv using C#


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

Solution

  • You can use linq to create two lists, one for each half then zip them into one IEnumerable as a comma separated string per element. Note that I had to make sure both lists are the same length by appending zero to the shorter list so the zip function takes all the elements in both lists. Then write that string into a csv file. The comma in the string means that an element like 112,78 will be automatically split into two columns with the number before the comma in the first column and the number after the comma in the second column. The code below is tested and it works. I have also attached an image of the csv file created.

    using System.IO;
    using System.Text;
    using System.Linq;
    using System.Collections.Generic;
    
                int[] pincodes = new int[] {1123, 677,098,666 };
                List<int> pincodes1 = new List<int>();
                List<int> pincodes2 = new List<int>();
                pincodes1 = pincodes.Take(pincodes.Length / 2).ToList();
                pincodes2 = pincodes.Skip(pincodes.Length / 2).ToList();
                if (pincodes1.Count > pincodes2.Count)
                    pincodes2.Add(0);
                else if (pincodes2.Count > pincodes1.Count)
                    pincodes1.Add(0);
    
                var bothpincodes = pincodes1.Zip(pincodes2, (first, second) => 
                  first + "," + second);
    
                using (StreamWriter sw = File.CreateText("mypinscombined.csv"))
                {
                    foreach (var item in bothpincodes)
                    {
                        sw.WriteLine(item);
                    }
                }
    
    

    The csv produced