Skip to content

Instantly share code, notes, and snippets.

@stivio00
Last active September 18, 2021 08:33
Show Gist options
  • Save stivio00/3c1df948253071b8e99233594fedd6ea to your computer and use it in GitHub Desktop.
Save stivio00/3c1df948253071b8e99233594fedd6ea to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using System.Data;
using System.Linq;
using System.Collections.Generic;
namespace DataTableTools
{
static class DataTableTools
{
public static DataTable CreateDataTableFromType<T>()
{
Type type = typeof(T);
DataTable dt = new DataTable(type.FullName);
dt.Columns.AddRange(type.GetProperties().Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
return dt;
}
public static void FillTable<T>(IEnumerable<T> en, DataTable dt)
{
Type type = typeof(T);
Dictionary<string,PropertyInfo> props = type.GetProperties().ToDictionary(p => p.Name);
foreach(T e in en)
{
DataRow dr = dt.NewRow();
foreach(DataColumn col in dt.Columns)
{
dr[col.ColumnName] = props[col.ColumnName].GetValue(e);
}
if(!dr.ItemArray.All(x => x == null))
{
dt.Rows.Add(dr);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment