.NET - 将通用集合转换为数据表 [英] .NET - Convert Generic Collection to DataTable
问题描述
我正在尝试将通用集合(列表)转换为数据表.我找到了以下代码来帮助我做到这一点:
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<>.
如何使用类中的 Nullable 属性/字段执行此操作?
How can I do this with Nullable properties/fields in my class?
推荐答案
那么大概你需要将它们提升到不可为空的形式,使用 Nullable.GetUnderlyingType
,并且可能改变一些null
值到 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屋!