【问题标题】:convert an object (list of strings) into data table将对象(字符串列表)转换为数据表
【发布时间】:2019-09-28 21:17:51
【问题描述】:

我正在使用 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;
}

【问题讨论】:

  • 请修改您的问题,至少显示您一直在使用的内容。
  • 更新。我得到 System.Collections.Generic.List`1[System.String] 这个在行中作为数据
  • 去掉try catch是隐藏异常

标签: c# asp.net datatable


【解决方案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;
    }

【讨论】:

    【解决方案2】:

    你的问题是你在它的开头添加了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

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 2019-01-17
      • 1970-01-01
      • 2018-05-01
      相关资源
      最近更新 更多