given a csv file with column "first_name" and "last_name", add a new column called full_name in csharp

To add a new column called full_name to a CSV file with columns first_name and last_name using C#, you can use the following steps:

  1. Read the CSV file and get the header row
  2. Add a new column header called full_name to the header row
  3. Iterate through each row of the CSV file and concatenate the first name and last name into a new column called full_name
  4. Write the updated CSV file with the new full_name column added

Here's the code to implement those steps:

main.cs
using System;
using System.IO;
using System.Linq;

class Program {
    static void Main(string[] args) {
        string csvFilePath = "your_csv_file_path.csv";
        string newCsvFilePath = "new_csv_file_path.csv";
        
        // 1. Read the CSV file and get the header row
        string[] csvRows = File.ReadAllLines(csvFilePath);
        string[] headerRow = csvRows.First().Split(',');
        
        // 2. Add a new column header called `full_name` to the header row
        headerRow = headerRow.Concat(new string[] { "full_name" }).ToArray();
        
        // 3. Iterate through each row of the CSV file and concatenate the first name and last name into a new column called `full_name`
        string[] updatedCsvRows = new string[csvRows.Length];
        updatedCsvRows[0] = string.Join(",", headerRow); // add the updated header row to the new CSV file
        for (int i = 1; i < csvRows.Length; i++) {
            string[] row = csvRows[i].Split(',');
            string fullName = $"{row[0]} {row[1]}"; // concatenate the first name and last name into a new column called `full_name`
            row = row.Concat(new string[] { fullName }).ToArray(); // add the `full_name` column to the row
            updatedCsvRows[i] = string.Join(",", row);
        }
        
        // 4. Write the updated CSV file with the new `full_name` column added
        File.WriteAllLines(newCsvFilePath, updatedCsvRows);
    }
}
1437 chars
31 lines

gistlibby LogSnag