Linq to CSV code example

177 views
Skip to first unread message

shriop

unread,
Jul 13, 2008, 1:27:54 AM7/13/08
to CSVChat
Here's an example of how to use Linq with DataStreams, http://www.csvreader.com/
, to query a csv file.

format of customers.csv:

id,first,last
1,Bruce,Dunwiddie
2,John,Doe

c# example:

using System;
using System.Collections.Generic;
using System.Linq;

using DataStreams.Csv;

namespace LinqToCsv
{
public class Example
{
static void Main(string[] args)
{
var customers =
from c in GetCustomers("customers.csv")
where c.LastName != "Dunwiddie"
select c;

foreach (var customer in customers)
{
Console.WriteLine("ID: " + customer.ID);
Console.WriteLine("First: " + customer.FirstName);
Console.WriteLine("Last: " + customer.LastName);
Console.WriteLine();
}

Console.ReadLine();
}

private struct Customer
{
public int ID;
public string FirstName;
public string LastName;
}

private static IEnumerable<Customer> GetCustomers(string
filename)
{
using (CsvReader reader = new CsvReader(filename))
{
reader.ReadHeaders();

while (reader.ReadRecord())
{
yield return new Customer(){
ID = Int32.Parse(reader["id"]),
FirstName = reader["first"],
LastName = reader["last"]};
}
}
}
}
}
Reply all
Reply to author
Forward
0 new messages