Monday, July 21, 2008

Using LINQ to Read a CSV File

I recently wrote a windows application which plots my checking account balance on a graph. In this application, I needed to import the financial data from a CSV (comma separated values) file. LINQ's ability to iterate over a collection of objects made this task easy:

IEnumerable lines = File.ReadAllLines("c:\checking.csv");

var query = from line in lines
let x = line.Split(',') //x will be a new, anonymous type
where x[0].Length > 0 //skip blank lines
select new
{
Date = DateTime.Parse(x[0].Replace("\"", string.Empty)), //remove double quotes
Description = x[4].Replace("\"", string.Empty),
Amount = Convert.ToDecimal(x[1].Replace("\"", string.Empty))
};

foreach(var i in query)
{
Console.WriteLine("Date: " + i.Date.ToString());
Console.WriteLine("Desc: " + i.Description);
Console.WriteLine("Amount: " + i.Amount.ToString());
}