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 ...
}

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

2 thoughts on “Read CSV file into LINQ”

  1. 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.

Leave a Reply