Created
January 15, 2016 14:57
-
-
Save davidegironi/9348c74c01d979942901 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
#region License | |
// Copyright (c) 2014 Davide Gironi | |
// | |
// Please refer to LICENSE file for licensing information. | |
#endregion | |
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Reflection; | |
namespace DG.Data.Model.Helpers | |
{ | |
public static class DGDataTableUtils | |
{ | |
/// <summary> | |
/// Convert an IEnumerable objet to a DataTable source | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="items"></param> | |
/// <returns></returns> | |
public static DataTable ToDataTable<T>(this IEnumerable<T> items) | |
{ | |
// Create the result table, and gather all properties of a T | |
DataTable table = new DataTable(typeof(T).Name); | |
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); | |
// Add the properties as columns to the datatable | |
foreach (var prop in props) | |
{ | |
Type propType = prop.PropertyType; | |
// Is it a nullable type? Get the underlying type | |
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) | |
propType = new NullableConverter(propType).UnderlyingType; | |
table.Columns.Add(prop.Name, propType); | |
} | |
// Add the property values per T as rows to the datatable | |
foreach (var item in items) | |
{ | |
var values = new object[props.Length]; | |
for (var i = 0; i < props.Length; i++) | |
values[i] = props[i].GetValue(item, null); | |
table.Rows.Add(values); | |
} | |
return table; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment