首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >.NET -将泛型集合转换为DataTable

.NET -将泛型集合转换为DataTable
EN

Stack Overflow用户
提问于 2009-03-31 14:27:00
回答 5查看 78.6K关注 0票数 80

我正在尝试将泛型集合(列表)转换为DataTable。我找到了以下代码来帮助我做到这一点:

// 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的一个属性更改为可以为空的类型时,我得到了以下错误:

DataSet does not support System.Nullable<>.

如何在我的类中使用可以为空的属性/字段来实现这一点?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-03-31 14:33:21

然后,您可能需要使用Nullable.GetUnderlyingType将它们提升到不可为空的形式,并可能将一些null值更改为DbNull.Value...

将分配更改为:

row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

在添加要添加的列时:

table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
            prop.PropertyType) ?? prop.PropertyType);

而且它是有效的。(??是空合并运算符;如果第一个操作数非空,它将使用第一个操作数,否则将计算并使用第二个操作数)

票数 140
EN

Stack Overflow用户

发布于 2009-03-31 14:34:26

井。由于DataSet不支持可以为空的类型,因此您必须检查该属性是否为泛型类型,获取该类型的泛型定义,然后使用Nullable.GetUnderlyingType获取参数(即实际类型)。如果值为空,只需在DataSet中使用DBNull.Value即可。

票数 5
EN

Stack Overflow用户

发布于 2009-03-31 14:34:29

如果给定prop.PropertyTypeNullable.GetUnderlyingType()返回非空值,则使用该值作为列的类型。否则,使用prop.PropertyType本身。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/701223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档