创建动态对象对象、动态

2023-09-03 00:34:19 作者:指着心说,我专属你

如何动态地创建对象?

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);
}

虚类(类不在code可用):

class Employee
{
    string EmpName { get;set; }
    string EmpID { get;set; }
    string PhoneNo { get;set; }
}

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

Note: Property/column names are dynamic.

现在我要转换的名单,其中,字典&LT;字符串,对象&gt;&GT; 类类型的名单,其中,对象&gt; (IE)名单,其中,员工和GT;

Now I want to convert the List<Dictionary<string, object>> to a class of type List<object> (i.e) List<Employee>.

是否有可能?建议请。

推荐答案

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

Using an anonymous object (if you know the properties you want to project):

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

或者,使用Expando的(如果你需要动态地预测未知的列名):

Or, using Expando (if you need to dynamically project unknown column names):

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);
}