创建动态对象

Ram*_*rai 7 .net c# list dynamic object

如何动态创建对象?

string[] columnNames = { "EmpName", "EmpID", "PhoneNo" };
List<string[]> columnValues = new List<string[]>();
for (int i = 0; i < 10; i++)
{
    columnValues.Add(new[] { "Ramesh", "12345", "12345" });
}

List<Dictionary<string, object>> testData = new List<Dictionary<string, object>>();

foreach (string[] columnValue in columnValues)
{
    Dictionary<string, object> data = new Dictionary<string, object>();
    for (int j = 0; j < columnNames.Count(); j++)
    {
        data.Add(columnNames[j], columnValues[j]);
    }
    testData.Add(data);
}
Run Code Online (Sandbox Code Playgroud)

虚构类(代码中没有类):

class Employee
{
    string EmpName { get;set; }
    string EmpID { get;set; }
    string PhoneNo { get;set; }
}
Run Code Online (Sandbox Code Playgroud)

注意:属性/列名称是动态的.

现在我想将其转换List<Dictionary<string, object>>为类型List<object>(即)List<Employee>.

可能吗?建议请.

Tet*_*Oni 21

使用匿名对象(如果您知道要投影的属性):

var employees = 
    (from dict in testData 
        select new 
        { 
            EmpName = dict["EmpName"] as string, 
            EmpID= dict["EmpID"] as string, 
            PhoneNo=dict["PhoneNo"] as string 
        }).ToList();
Run Code Online (Sandbox Code Playgroud)

或者,使用System.Dynamic.Expando(如果需要动态投影未知的列名):

string[] columnNames = { "EmpName", "EmpID", "PhoneNo" };
List<string[]> columnValues = new List<string[]>();
for (int i = 0; i < 10; i++)
{
    columnValues.Add(new[] { "Ramesh", "12345", "12345" });
}

var testData = new List<ExpandoObject>();

foreach (string[] columnValue in columnValues)
{
    dynamic data = new ExpandoObject();
    for (int j = 0; j < columnNames.Count(); j++)
    {
        ((IDictionary<String,Object>)data).Add(columnNames[j], columnValue[j]);
    }
    testData.Add(data);
}
Run Code Online (Sandbox Code Playgroud)

  • 问题是类`Employee`不存在.如果我正确理解了问题,属性/列名称也是动态的 (4认同)