如何动态创建对象?
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);
}
虚类(类在代码中不可用):
class Employee
{
string EmpName { get;set; }
string EmpID { get;set; }
string PhoneNo { get;set; }
}
注意:属性/列名称是动态的。
现在我想转换 List<Dictionary<string, object>>
到一类类型 List<object>
(即)List<Employee>
.
这可能吗?请提出建议。
最佳答案
使用匿名对象(如果您知道要投影的属性):
var employees =
(from dict in testData
select new
{
EmpName = dict["EmpName"] as string,
EmpID= dict["EmpID"] as string,
PhoneNo=dict["PhoneNo"] as string
}).ToList();
或者,使用 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);
}
关于c# - 创建动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12427280/