如下链接所述,我已成功将List<T>
转换为DataTable
,但还有更多的问题。我的T对象
基本上是一个自定义类,具有属性和对另一个类的引用。现在我需要将该类的属性添加到datatable中。
这是函数
public static DataTable ToDataTable<T>(this IList<T> list)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor prop = properties[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = properties[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
return table;
}
这是我努力定制的结果,但无法检索
DataTable
的整个数据行,因为T没有其子级的属性。如何添加T
的子属性或获取整个数据行。private static DataTable AddColumnsForProperties(DataTable dt, PropertyDescriptor p, ref List<PropertyDescriptor> properties)
{
if (p.PropertyType.Namespace.ToLower().StartsWith("mynamespace"))
{
var allProperties = p.GetChildProperties();
foreach (PropertyDescriptor item in allProperties)
{
if (item.PropertyType.Namespace.ToLower().StartsWith("mynamespace"))
AddColumnsForProperties(dt, item, ref properties);
else
if (!dt.Columns.Contains(item.Name))
{
dt.Columns.Add(item.Name, Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType);
properties.Add(item);
}
}
}
else
if (!dt.Columns.Contains(p.Name))
{
dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
properties.Add(p);
}
return dt;
}
public static DataTable ToDataTable<T>(this IList<T> list)
{
DataTable table = null;
if (list != null && list.Count > 0)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
List<PropertyDescriptor> propList = new List<PropertyDescriptor>();
table = new DataTable();
foreach (PropertyDescriptor item in properties)
{
AddColumnsForProperties(table, item, ref propList);
}
object[] values = new object[propList.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = propList[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
}
return table;
}
我正在开发一个自定义的网格控件,它只能在 DataTable
上工作,因此这个功能对我来说非常关键。由于有很多需要定制的网格,我需要拥有这个函数,我不能手动创建每一个 DataTable
。