se csv file and add a column in csharp

To read a CSV file and add a column, you can use the following steps:

  1. Install the CsvHelper package from NuGet using the following command:
main.cs
Install-Package CsvHelper
26 chars
2 lines
  1. Add the CsvHelper namespace to your code by including the following line:
main.cs
using CsvHelper;
17 chars
2 lines
  1. Define a class that represents the data in a row of the CSV file. For example, if the CSV file contains columns "Name" and "Age", you can define a class like this:
main.cs
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
94 chars
6 lines
  1. Use the CsvHelper library to read the CSV file into a list of Person objects. Here's an example code snippet:
main.cs
using (var reader = new StreamReader("path/to/file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Person>().ToList();
}
185 chars
6 lines
  1. Add a new property to the Person class to represent the new column you want to add. For example, if you want to add a "Salary" column, you can modify the class like this:
main.cs
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public double Salary { get; set; }
}
133 chars
7 lines
  1. Use LINQ to update the new property in each Person object in the list. For example, you can set a default salary of $50,000 like this:
main.cs
records.ForEach(p => p.Salary = 50000);
40 chars
2 lines
  1. Use CsvHelper to write the modified list back to a new CSV file. Here's an example code snippet:
main.cs
using (var writer = new StreamWriter("path/to/newfile.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}
166 chars
6 lines

gistlibby LogSnag