This is a super simple way of reading CSV in linqpad, it won't handle every situation (I'll cover more ways in future posts), but it's pretty handy.
Lets say we have the following CSV:
ID,Name,Email
1,alex,alex@example.org
2,bob,bob@example.org
3,fred,fred@example.org
The first step is to click "my extensions" on the bottom left hand corner of linqpad.
Now copy the following c# code (sourced from: stackoverflow) in the "my extensions" class in linqpad:
The advantage of this rather than simply reading all lines is that it will load the file line by line and using the yield keyword will stop if finds what you need (rather than reading the whole file).
public static IEnumerable ReadFrom(string file)
{
string line;
using(var reader = File.OpenText(file))
{
while((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
Remember to press F5 in the my expressions window to compile it.
You can now very easily read the CSV in linqpad using the following linq query (in expression syntax):
Hover over to see descriptions
var csvData =
from row in MyExtensions.ReadFrom(@"c:\sample.csv").Skip(1)
let columns = row.Split(',')
select new
{
ID = int.Parse(columns[0]),
Name = columns[1],
Email = columns[2]
};
csvData.Dump();
Now when you press F5 in LinqPad your CSV will be displayed in a nicely formatted table:
You can then parse the CSV in with normal linq queries, for example this simple linq expression will find people whose name "alex". Please note the intellisense drop down will only in linqpad pro edition (certainly worth the money if you ask me!)
var alexs = from csv in csvData
where csv.Name.Contains("alex")
select csv;
I have found this sort of technique especially useful when comparing on an adhoc basis if CSV data was successfully imported via SSIS etc. This technique won't handle quoted CSV, but let me know and I'll post a follow up with more in-depth CSV handling techniques or perhaps if you want me to cover linqpad further.