Free Information Technology Magazines and eBooks

Thursday, May 28, 2009

Read data from CSV using LINQ

Read data from CSV using LINQComma-separated values (CSV) file is the most common used format to exchange data between spreadsheet program and a database program which I previously discussed on my article about Reading CSV file into an array. On this post, you will learn How to read data from CSV using the popular Language Integrated Query or LINQ. The complete source code of the sample project used on this article is downloadable here.


The sample project I created perform the following tasks:
1. Ask for CSV file location.
2. Read the data from CSV file and put it on ListView control.

CSV format used is:
1,fryan,valdez,fryanv@fryan0911.com
2,Test,Test,test@fryan0911.com
3,Sample,Sample,sample@fryan0911.com


Make sure you already included the following namespaces

using System.Linq;
using System.IO;


To retrieve data from CSV file, use the following code:

string[] csvlines = File.ReadAllLines(@txtCSVFile.Text);

var query = from csvline in csvlines
let data = csvline.Split(',')
select new
{
ID = data[0],
FirstName = data[1],
LastName = data[2],
Email = data[3]
};



Take note of the new keyword "let" which is used inside LINQ queries to create temporarily variables.

To view the sample Visual Studio 2008 project. Download it from here.

LINQ to CSV

For more LINQ coding tips, subscribe now

2 comments:

JoshW said...

This approach is not perfect for CSV rules, because a CSV can have commas in the middle of a field or new lines in the middle of a field.

Considering how common CSV's are, it is too bad that Microsoft didn't include this basic functionality built-in.

Anonymous said...

Yeah the format of my CSV is:
"value 1", "another, value", "value 3"

3 columns. Split ends up with this:
value 1
another
value
value 3

:(

Crash Smoke.