Last active
September 18, 2021 08:33
-
-
Save stivio00/3c1df948253071b8e99233594fedd6ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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