Created
October 9, 2012 13:29
-
-
Save bobbychopra/3858824 to your computer and use it in GitHub Desktop.
Converts a Generic Enumerable to a DataTable
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.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