Following on from my post on using anonymous types to build strongly typed sql queries, here’s one on extracting data from csv files into a data structure of your choosing.
Suppose we have a CSV file like this:
Date,Bank,Account,Description,In,Out,Category
"2010-07-21","Halifax Online (UK)","Halifax Current Account","Direct Debit - Ukonline","","£9.99","Utilities & bills"
"2010-06-21","Halifax Online (UK)","Halifax Current Account","Direct Debit - Ukonline","","£9.99","Utilities & bills"
Using my snazzy new method, we can parse it into an array of anonymous-typed objects using some code like this:

Wow. Notice that the DateColumn is an actual DateTime object, not just a string. So what just happened? Basically, the type defined in the call to FromCsv is interrogated using reflection, the name of each parameter is matched up to the correct column from the CSV file, and the value converted into the correct Type using Convert.ChangeType.
Here’s the code. Do with it what you will.
IEnumerable<T> FromCsv<T>(T template, string csv)
{
using (var ms = new MemoryStream()){
using (var sw = new StreamWriter(ms)){
sw.Write(csv);
sw.Flush();
ms.Seek(0, SeekOrigin.Begin);
var tfp = new Microsoft.VisualBasic.FileIO.TextFieldParser(ms){
Delimiters = new[] {","}, HasFieldsEnclosedInQuotes = true
};
var headers = tfp.ReadFields();
var @params = typeof(T).GetConstructors().Single().GetParameters().Select (p => new {Type = p.ParameterType, Index = Array.IndexOf(headers, p.Name)}).ToArray();
while(!tfp.EndOfData){
var data = tfp.ReadFields();
yield return (T) Activator.CreateInstance(typeof(T), @params.Select(p => Convert.ChangeType(data[p.Index], p.Type)).ToArray());
}
}
}
}
Note the use of TextFieldParser, the MS way to get at your CSVs. If you don’t like the VisualBasic namespace, feel free to do it some other way.