Saturday, January 31, 2009

Read CSV file into LINQ

This article is based on the great book of LINQ in Action. I am learning so much from it and I would like to keep a note of some handy subject from the book while not disturbing any copyright of ther authors. For the full story please buy the book from http://www.manning.com/LINQinAction.

 
using (StreamReader reader = new StreamReader("books.csv"))
{
var books =
from line in reader.Lines()
where !line.StartsWith("#")
let parts = line.Split(',')
select new {
Title = parts[1],
Publisher = parts[3],
Isbn = parts[0]
};

// use the books here ...
}

2 comments:

Chris Nicola said...

Sorry to necro your post, but I was curious. Where did you find this StreamReader.Lines() function. It does not appear to be part of .NET 3.5.

Alex said...

Hi Asghar, nice post.

In case anyone comes across this, I believe chnicola is right, and perhaps Lines() should instead be ReadAllLines() ?? Is that right?

You might like my post on a similar topic reading CSV in Linq. Except I've used a slightly different technique using an enumerator and yield keyword (inspired by a stackoverflow.com post) so that the CSV file is only read line by line instead of the whole file. I've done the example in linqpad but it's a similar idea:

Read CSV with LinqPad.

Let me know what you think.