Skip to content

Instantly share code, notes, and snippets.

@azizkale
Created May 2, 2020 02:41
Show Gist options
  • Save azizkale/ae6ceff4d308960d02e07df4e4fe6587 to your computer and use it in GitHub Desktop.
Save azizkale/ae6ceff4d308960d02e07df4e4fe6587 to your computer and use it in GitHub Desktop.
A Function for Convertiing From JSON to DataTable
public static DataTable ToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment