Skip to content

Instantly share code, notes, and snippets.

@margusmartsepp
Created September 11, 2014 07:10
Show Gist options
  • Select an option

  • Save margusmartsepp/2643e248f5bc46450243 to your computer and use it in GitHub Desktop.

Select an option

Save margusmartsepp/2643e248f5bc46450243 to your computer and use it in GitHub Desktop.
DataTable to json
//add reference System.Data
//add reference System.Web.extensions
//add reference System.Web.DataTableExtensions
public static string ConvertToJson(DataTable dt, int page = 0, int count = 100)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var rows = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.AsEnumerable().Skip(page * count).Take(count).ToList())
{
rows.Add(dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => dr[col]));
}
return serializer.Serialize(rows);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment