Skip to content

Instantly share code, notes, and snippets.

@davefancher
Created February 4, 2016 18:09
Show Gist options
  • Save davefancher/03e78ed7429e3d9ad0dc to your computer and use it in GitHub Desktop.
Save davefancher/03e78ed7429e3d9ad0dc to your computer and use it in GitHub Desktop.
// LINQPad Example
// Updated from http://davefancher.com/2010/04/16/linq-ienumerable-to-datatable/
// Defines an extension method that creates a new System.Data.DataTable from an IEnumerable<T>
// Even works with anonymous types
public static class IEnumerableExtensions
{
public static DataTable ConvertToDataTable<TSource>(this IEnumerable<TSource> source)
{
var props = typeof(TSource).GetProperties();
var dt = new DataTable();
foreach (var p in props)
{
dt.Columns.Add(p.Name, p.PropertyType);
}
foreach (var r in source)
{
dt.Rows.Add(props.Select(p => p.GetValue(r, null)).ToArray());
}
return dt;
}
}
void Main()
{
new[] {
new { ID = 1, Name = "Dave", DOB = DateTime.Parse("1978-08-02"), Amount = 1.23d, Flag = true },
new { ID = 2, Name = "Fancher", DOB = DateTime.Parse("2001-02-03"), Amount = 2.34d, Flag = false }
}.ConvertToDataTable()
.Dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment