Wednesday, October 14, 2009

Linq on DataTable Query

Today I have to serialize the DataTable to JSON.
I get the cyclic reference error using the following code:
string example = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(dt);

After googling, I find that we cannot serialize a dataTable directly using the JavaScriptSerializer provided. Some webs implement their own code for dataTable.

But I finally have a fine solution - use Linq to Query DataTable:
string example = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(dt.AsEnumerable());

Also if you just want specific columns, you can do the following query:
var dataToSerialize = from p in ct.AsEnumerable()
select new{ Column1 = c.Field("c1");}

Reference:
http://blogs.msdn.com/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx

No comments: