Skip to content

Instantly share code, notes, and snippets.

@Programazing
Created April 18, 2019 15:38
Show Gist options
  • Save Programazing/9d4cd4a2af6b0eec5cece80228d59b1e to your computer and use it in GitHub Desktop.
Save Programazing/9d4cd4a2af6b0eec5cece80228d59b1e to your computer and use it in GitHub Desktop.
An extension method to convert a List of any type to a DataTable.
public static DataTable ToDataTable<T>(this List<T> input)
{
var props = TypeDescriptor.GetProperties(typeof(T));
var output = new DataTable();
foreach(PropertyDescriptor item in props)
{
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
output.Columns.Add(item.Name, item.PropertyType.GetGenericArguments()[0]);
else
output.Columns.Add(item.Name, item.PropertyType);
}
var values = new object[props.Count];
foreach (T item in input)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
output.Rows.Add(values);
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment