如何将列表(T)转换为数据表 [英] How to convert list (Of T) to a Data Table
本文介绍了如何将列表(T)转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
谁能帮助我如何转换list< Of T>到.net中的数据表
在此先感谢
Seshu
Hi All,
Can anyone help me how to convert list<Of T> to a DataTable in .net
Thanks in Advance
Seshu
推荐答案
将泛型列表转换为数据表 [ ^ ]
使用泛型和属性从集合到数据表的投射 [
Convert a Generic List to a Datatable[^]
Casting from a Collection to a Data Table using Generics and Attributes[^]
这是一种扩展方法就是这样:
Here is an extension method which does just that:
public static class ExtensionMethods
{
/// <summary>
/// Converts a List to a datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dt.Columns.Add(property.Name, property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
}
仔细检查那里的线程 [ ^ ]中建议使用BindingList<T>
BindingList< T> [
Have a go through the threads going there[^] where its suggested to useBindingList<T>
BindingList<T>[^] Class Provides a generic collection that supports data binding.
or the given function also might help you to convert List<type> to datatable
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
这篇关于如何将列表(T)转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文