将动态列表转换为数据表

时间:2019-02-19 06:31:08

标签: c# list dynamic reflection datatable

我有以下格式的动态列表,想转换成数据表。

动态背后的原因是,此输入中的列将保持变化。

输入:

{{
  "EMP_ID": "12345",
  "Client": "abcdef",
  "Business_Type": "Temping",
  "EMP NO": "098765",
  "Associate Id": "mki0987"
}}

上面的列表是从json字符串生成的

{[  {    
 "EMP_ID": "12345",   
 "Client": "abcdef",   
 "Business_Type": "Temping",   
 "EMP NO": "098765",   
 "Associate Id": "mki0987"
 }]}

预期输出:

EMP_ID  | Client  |  Business_Type  |  EMP NO  |  Associate ID

--------|---------|-----------------|----------|-------------------

12345   | abcdef  |   Temping       | 098765   |   mki0987

--------|---------|-----------------|----------|-------------------

实现这一目标的任何想法。


我尝试过使用反射进行此操作,如下所述

public static DataTable ToDataTable<T>(List<T> items) {
    DataTable dataTable = new DataTable(typeof(T).Name);

    //Get all the properties
    PropertyInfo[] Props = typeof(T).GetProperties();
    foreach (PropertyInfo prop in Props) {
        //Defining type of data column gives proper data table
        //var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
        //Setting column names as Property names
        dataTable.Columns.Add(prop.Name);
    }
    foreach (T item in items) {
        var values = new object[Props.Length];
        for (int i = 0; i < Props.Length; i++) {
            //inserting property values to datatable rows
            values[i] = Props[i].GetValue(item, null);
        }
        dataTable.Rows.Add(values);
    }
    //put a breakpoint here and check datatable
    return dataTable;
}

但是在此特定代码中,Get属性不会以列名的形式返回任何内容

0 个答案:

没有答案
相关问题