译:泛型List集合转化为DateTable的扩展方法

时间:2023-03-09 09:52:03
译:泛型List集合转化为DateTable的扩展方法

译文出处:http://www.codeproject.com/Tips/867866/Extension-Method-for-Generic-List-Collection-to-Da

这段代码是能够帮助你把泛型集合List转出成DataTable的扩展方法。

背景:

不知道你是否知道这个扩展方法,但是你可以不做任何修改的去使用下面这个类的代码。

使用代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data; namespace coDEalers
{
public static class Extension
{
public static DataTable ListToDataTable<T>(this IList<T> data, string tableName)
{
DataTable table = new DataTable(tableName); //special handling for value types and string
if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
{ DataColumn dc = new DataColumn("Value");
table.Columns.Add(dc);
foreach (T item in data)
{
DataRow dr = table.NewRow();
dr[] = item;
table.Rows.Add(dr);
}
}
else
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name,
Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
try
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
catch (Exception ex)
{
row[prop.Name] = DBNull.Value;
}
}
table.Rows.Add(row);
}
}
return table;
}
}
}

优点(兴趣点):

这是一个把GenericList集合转化成DataTable的一个简单的方法。

用法:

DataTable dt = null;
List<StateList> stateListObj = JsonConvert.DeserializeObject<List<StateList>>(hdn_stateDetails_JSON.Value);
dt = stateListObj.ListToDataTable<StateList>("dtState");

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~