转换为List <dynamic>记录为空

时间:2017-06-08 13:24:20

标签: c# asp.net

enter image description here我正在尝试将我的List转换为DataTable,但转换记录时计数为0。

这是我的代码:

DataAccessProvider dap = new DataAccessProvider(
    Settings.Default.SQLServerConnection, 
    DatabaseType.MSSql);
var employees = dap.SelectAll("Employees").AsEnumerable().ToList();
DataTable Employees = new DataTable();
Employees = ToDataTable(employees);

public DataTable ToDataTable<T>(List<T> items)
{
    DataTable dataTable = new DataTable(typeof(T).Name);
    //Get all the properties
    PropertyInfo[] Props = typeof(T).GetProperties(
        BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo prop in Props)
    {
        //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;
}

public List<dynamic> SelectAll(string tableName)
{
    List<dynamic> result = new List<dynamic>();

    using (IDataReader reader = ExecuteReader("Select * From " + tableName))
    {
        while (reader.Read())
        {
            dynamic expando = new ExpandoObject();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                string columnName = reader.GetName(i);
                ((IDictionary<String, Object>)expando).Add(
                    columnName, 
                    reader[columnName]);
            }
            result.Add(expando);
        }
    }

    return result;
}

以上都是我的代码。当我调试时,我发现在ToDataTable函数中,Props计数为0.那么这里有什么问题?

2 个答案:

答案 0 :(得分:0)

dynamic个对象没有任何属性,更不用说公共实例属性了。

此代码输出零:

dynamic expando = new ExpandoObject();
((IDictionary<String, Object>)expando).Add(
                    "col", 
                   "val");
Console.WriteLine(expando.GetType().GetProperties().Length);

(实例:http://rextester.com/IOTK71323

如果要访问动态属性,则需要将其强制转换为写入的相同字典,并读取键/值:

dynamic expando = new ExpandoObject();
((IDictionary<String, Object>)expando).Add(
                    "col", 
                   "val");

var dict =  ((IDictionary<String, Object>)expando);
foreach(var kv in dict)
    Console.WriteLine("{0} = {1}", kv.Key,kv.Value);

(实例:http://rextester.com/RMAW17261

答案 1 :(得分:0)

考虑使用((IDictionary<String, object>)expando).Keys并将它们传递给使用这些键的新ToDataTable实现('属性名')。

对于您当前的Reflection解决方案,这是必要的,以查找属性名称(因为https://stackoverflow.com/a/32312740/34092状态,这将无效)。

Convert dynamic list to datatable c#也值得一读。