.NET - 转换泛型集合到数据表 [英] .NET - Convert Generic Collection to DataTable
问题描述
我想泛型集合(列表)转换为数据表。我发现下面的code帮我做到这一点:
I am trying to convert a generic collection (List) to a DataTable. I found the following code to help me do this:
// Sorry about indentation
public class CollectionHelper
{
private CollectionHelper()
{
}
// this is the method I have been using
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
public static DataTable CreateTable<T>()
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (PropertyDescriptor prop in properties)
{
// HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES
table.Columns.Add(prop.Name, prop.PropertyType);
}
return table;
}
}
我的问题是,当我改变MySimpleClass的特性之一,可空类型,我得到以下错误:
My problem is that when I change one of the properties of MySimpleClass to a nullable type, I get the following error:
的DataSet不支持System.Nullable&LT;方式&gt;
我如何在我的课这样做可空的属性/字段?
How can I do this with Nullable properties/fields in my class?
推荐答案
然后presumably你需要将它们提升到非空形式,使用 Nullable.GetUnderlyingType
,也许改变一些空
值 DbNull.Value
...
Then presumably you'll need to lift them to the non-nullable form, using Nullable.GetUnderlyingType
, and perhaps change a few null
values to DbNull.Value
...
更改任务是:
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
和添加列时是:
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
prop.PropertyType) ?? prop.PropertyType);
和它的作品。 ( ??
是空合并运算符;它使用第一个操作数,如果它是非空,否则第二个操作数的计算和使用)
And it works. (??
is the null-coalescing operator; it uses the first operand if it is non-null, else the second operand is evaluated and used)
这篇关于.NET - 转换泛型集合到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!