Sunday, January 4, 2009

Linq with text file

DataTable dt = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(
@"SELECT * FROM F:\myvfp\books.csv",
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\;
Extended Properties=""Text;HDR=No;FMT=Delimited"""))
{
da.Fill(dt);
}

var books = from b in dt.AsEnumerable()
select new
{
Title = b.Field<string>(0),
Publisher = b.Field<string>(1),
Year = b.Field<int>(2)
};
foreach (var book in books)
{
Console.WriteLine(string.Format("Title: {0}, Publisher: {1}, Year: {2}", book.Title, book.Publisher, book.Year));
}

Saturday, January 3, 2009

Linq with foxpro table

DataTable dt = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(@"select title as Title, publisher as Publisher, year as Year from books", @"Provider=VFPOLEDB.1;Data Source=c:\myvfp\"))
{
da.Fill(dt);
}

XElement xml = new XElement("books",
dt.AsEnumerable().Where(book =>
book.Field<int>("Year") == 2006)
.Select(book => new XElement("book",
new XAttribute(
"title",
book.Field<string>("Title")),
new XElement(
"publisher",
book.Field<string>("Publisher"))
))
);
Console.WriteLine(xml);

or

XElement xml = new XElement("books",
from book in dt.AsEnumerable()
where book.Field<int>("Year") == 2006
select new XElement("book",
new XAttribute("title", book.Field<string>("Title")),
new XElement("publisher", book.Field<string>("Publisher")
)));
Console.WriteLine(xml);


Instead of
from book in dt.AsEnumerable()
we can use
from DataRow book in dt.Rows