Skip to content

Instantly share code, notes, and snippets.

@bobbychopra
Created October 9, 2012 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobbychopra/3858824 to your computer and use it in GitHub Desktop.
Save bobbychopra/3858824 to your computer and use it in GitHub Desktop.
Converts a Generic Enumerable to a DataTable
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication
{
public static class DataTableUtil
{
public static DataTable ToDataTable<T>(this IEnumerable<T> enumerable)
{
var type = typeof(T);
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var dt = new DataTable();
props.ToList().ForEach(p => dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType));
enumerable.Select(r => props.Select(p => p.GetValue(r) ?? DBNull.Value).ToArray())
.ToList()
.ForEach(r => dt.Rows.Add(r));
return dt;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment