One liner CSV reader

I can't count how many times I had to read quickly (for small oneshot script purpose) a CSV file which was coming from powershell, database, Excel or anything else.

I can't count how many times I've wrote the following ugly & clunky lines

public class data  
{
    public Guid column1;
    public string column2;
}
[...]
List<data> content = new List<data>();  
string[] lines = System.IO.File.ReadAllLines("inputfile.csv");  
foreach(var line in lines)  
{
    string[] chunk = line.Split('\t');
    content.Add(new data { column1 = new Guid(chunk[0]), column2 = chunk[1] });
}

ok ... let's stop doing this, let's be adult & use LINQ

var content = System.IO.File.ReadAllLines("inputfile.csv")  
    .Select(x => x.Split('\t'))
    .Select(y => 
        new {
            column1 = new Guid(y[0]),
            column2 = y[1]
        });

As stated, these kind of lines are mainly used for one shot script, it's not robust/error proof at all.

Fabien Camous

Read more posts by this author.