【发布时间】:2015-11-20 10:00:38
【问题描述】:
Continuation from "Convert generic List/Enumerable to DataTable?"
我一直在使用以下代码将通用 List<T> 转换为 DataTable:
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
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)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
但是,我现在有一个列表List<foo>,其中foo 包含属性List<bar>(其中List<bar> 可以包含零值)。
问题:
我想转换一个泛型List<foo>,其中包含另一个泛型嵌套List<bar>,例如:
List<bar> GenericNestedList = new List<bar>{ new bar("barA"), new bar("barB") };
List<foo> GenericList = new List<foo> { new foo("fooA", GenericNestedList) };
生成DataTable:
| GenericProperty | GenericNestedProperty |
|-----------------|-----------------------|
| fooA | barA |
| fooA | barB |
原代码占foo内的很多属性,bar也会有这个要求。
到目前为止,我已经能够检索bar 的属性,但是当List<bar> 为空时,我无法弄清楚如何填充Datatable。我没有太多编写泛型方法的经验,所以我很抱歉不能提供我的很多工作。
其他示例:
列表
List<foo> GenericList = new List<foo> { new foo("fooB", new List<bar>()) };
数据表
| GenericProperty | GenericNestedProperty |
|-----------------|-----------------------|
| fooB | |
列表
List<bar> GenericNestedListA = new List<bar>{ new bar("barC"), new bar("barD") };
List<bar> GenericNestedListB = new List<bar> { new bar("barE"), new bar("barF") };
List<foo> GenericList = new List<foo> { new foo("fooC", GenericNestedListA),
new foo("fooD", GenericNestedListB) };
数据表
| GenericProperty | GenericNestedProperty |
|-----------------|-----------------------|
| fooC | barC |
| fooC | barD |
| fooD | barE |
| fooD | barF |
类:
富
class foo
{
public string GenericProperty;
public List<bar> GenericNestedList;
public foo(string GenericProperty, List<bar> GenericNestedList)
{
this.GenericProperty = GenericProperty;
this.GenericNestedList = GenericNestedList;
}
}
条形
class bar
{
public string GenericNestedProperty;
public bar(string GenericNestedProperty)
{
this.GenericNestedProperty = GenericNestedProperty;
}
}
【问题讨论】:
标签: c# list generics datatable