将对象(字符串列表)转换为数据表

时间:2019-09-28 21:17:51

标签: c# asp.net datatable

我正在使用C#和.net内核。我有一个包含多个字符串列表的对象,我想将此对象转换为数据表。

我已经尝试过此代码,但是失败了:

public static DataTable ObjectToData(object o)
{
    DataTable dt = new DataTable("OutputData");

    DataRow dr = dt.NewRow();
    dt.Rows.Add(dr);

    o.GetType().GetProperties().ToList().ForEach(f =>
    {
        try
        {
            f.GetValue(o, null);
            dt.Columns.Add(f.Name, typeof(string));
            dt.Rows[0][f.Name] = f.GetValue(o, null);
        }
        catch { }
    });
    return dt;
}

2 个答案:

答案 0 :(得分:1)

您的问题是您在DataRow的开头添加了它。您要做的是实例化它,然后分配值,最后将其添加到数据表中。 还将添加信息更改为下一个dr[f.Name] = f.GetValue(o, null);

的行

代码如下:

public static DataTable ObjectToData(object o)
{
    DataTable dt = new DataTable("OutputData");

    DataRow dr = dt.NewRow();


    o.GetType().GetProperties().ToList().ForEach(f =>
    {
        try
        {
            f.GetValue(o, null);
            dt.Columns.Add(f.Name, typeof(string));
            dr[f.Name] = f.GetValue(o, null);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    });

    dt.Rows.Add(dr);

    return dt;
}

您可以在https://dotnetfiddle.net/EeegHg

中找到示例

答案 1 :(得分:1)

通用转换:

public DataTable ListToDataTable<T>(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;
    }