Saturday, February 21, 2009

Load a DataTable with LINQ

The other day a colleague of mine needed to load a strongly typed ADO.NET DataTable from a LINQ to SQL query. We didn't find any good solutions using "The Google", so after a bit of hacking we came up with something similar to this:

    PeopleDataSet ds = new PeopleDataSet();
    using (PeopleDataContext context = new PeopleDataContext())
    {
        (from p in context.Persons
         select new
                    {
                        Row = ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName)
                    }).ToList();

    }

After ToList() executes we should have a DataTable populated with the results of our query.

#    Comments [0] |