Skip to content

Instantly share code, notes, and snippets.

@gcapnias
Created January 8, 2021 17:10
Show Gist options
  • Select an option

  • Save gcapnias/4fa6251f285c85eb1cbfd13f214fa7e2 to your computer and use it in GitHub Desktop.

Select an option

Save gcapnias/4fa6251f285c85eb1cbfd13f214fa7e2 to your computer and use it in GitHub Desktop.
Convert an IList<T> to DataTable
public static partial class Extensions
{
public static DataTable ToDataTable<T>(this 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];
DataColumn column = table.Columns.Add(prop.Name, prop.PropertyType);
var displayname = prop.Attributes.OfType<DisplayNameAttribute>().FirstOrDefault();
if (displayname != null)
{
column.Caption = displayname.DisplayName;
}
}
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