reorder the columns of a csv file in csharp

To reorder the columns of a CSV file in C#, you can use the Linq library to read the file, reorder the columns, and write them out to a new file.

Assuming your CSV file has a header row with column names and the columns you want to reorder are known ahead of time, you could use the following code:

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

string inputFile = "input.csv";
string outputFile = "output.csv";

// columns to include and reorder
string[] columns = new string[] {
    "Column3",
    "Column1",
    "Column2"
};

// read input file as an array of strings (rows)
string[] rows = File.ReadAllLines(inputFile);

// split each row by comma and project into a new object with column values as properties
var data = from row in rows
           let fields = row.Split(',')
           select new {
               Column1 = fields[0],
               Column2 = fields[1],
               Column3 = fields[2]
           };

// select columns to include and materialize into array of arrays
var output = data.Select(d => columns.Select(c => d.GetType().GetProperty(c).GetValue(d, null)).ToArray()).ToList();

// write output array to a new CSV file
File.WriteAllLines(outputFile, output.Select(x => string.Join(",", x)));
916 chars
31 lines

This code reads the CSV file into an array of strings, then uses Linq to project each row into an anonymous object with properties for each column. The order of the properties in the object is the same as the order of the columns in the input CSV file.

Then, the code selects the columns to include and materializes the data into an array of arrays for writing out to the new CSV file. Finally, it writes the output array to a new CSV file using the File.WriteAllLines method.

Note that this code assumes that the input CSV file and the output CSV file are UTF-8 encoded with no BOM. If your file encoding is different, you may need to specify the encoding in the File.ReadAllLines and File.WriteAllLines methods.

gistlibby LogSnag