#region Web Extensions Method ToDataTable
///
/// Convert a List{T} to a DataTable.
///

public static DataTable ToDataTable(List items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}

foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++) values[i] = props[i].GetValue(item, null);
tb.Rows.Add(values);
}

return tb;
}

///
/// Determine of specified type is nullable
///

private static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}

///
/// Return underlying type if type is Nullable otherwise return the type
///

private static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType) return t;
else return Nullable.GetUnderlyingType(t);
}
else return t;

}
#endregion


Linq:轉換成 DataTable
http://www.dotblogs.com.tw/asdtey/archive/2010/03/11/linqtodatatable.aspx


using System.Collections;
using System.Data;
using System.Reflection;

///
/// IEnumerable 擴充方法
///

public static class IEnumerableExtensions
{
///
/// 將 IEnumerable 轉換至 DataTable
///

/// IEnumerable
/// DataTable
public static DataTable ToDataTable(this IEnumerable list)
{
DataTable dt = new DataTable();
bool schemaIsBuild = false;
PropertyInfo[] props = null;

foreach (object item in list)
{
if (!schemaIsBuild)
{
props = item.GetType().GetProperties();
foreach (var pi in props)
{
dt.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
}

schemaIsBuild = true;
}

var row = dt.NewRow();
foreach (var pi in props)
{
row[pi.Name] = pi.GetValue(item, null);
}

dt.Rows.Add(row);
}

dt.AcceptChanges();
return dt;
}
}

arrow
arrow
    全站熱搜

    altubers 發表在 痞客邦 留言(1) 人氣()