我在运行时创建动态列表,执行后我需要将列表分配给我的类属性
List<tblchargemaster> charge = new List<tblchargemaster>();
charge = (List<tblchargemaster>) ObjDB.SelectQuery("tblchargemaster");
tblchargemaster
是类类型,SelectQuery
函数返回List<dynamic>
。如何将此动态列表转换为具有类类型的列表?
public List<dynamic> SelectQuert(string TableName)
{
Conn.Open();
DataTable dt = new DataTable("map");
string Query = "Select * from " + TableName;
MySqlDataAdapter dr = new MySqlDataAdapter(Query, Conn);
dr.Fill(dt);
List<dynamic> dynamicDt = dt.ToDynamic();
Conn.Close();
return dynamicDt;
}
通用类是
public static class DataTableExtensions
{
public static List<dynamic> ToDynamic(this DataTable dt)
{
var dynamicDt = new List<dynamic>();
foreach (DataRow row in dt.Rows)
{
dynamic dyn = new ExpandoObject();
foreach (DataColumn column in dt.Columns)
{
var dic = (IDictionary<string, object>)dyn;
dic[column.ColumnName] = row[column];
dynamicDt.Add(dyn);
}
}
return dynamicDt;
}
}
答案 0 :(得分:6)
编辑,因为不支持从动态到强类型的显式转换。
var charge = ObjDB.SelectQuert("tblchargemaster").Cast<tblchargemaster>();
变为:
var charge = ObjDB.SelectQuert("tblchargemaster").Select(CastDynamicTo<tblchargemaster>)
而CastDynamicTo<tblchargemaster>
是通过Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?
答案 1 :(得分:2)
使用Cast<tblchargemaster>()
方法:
List<tblchargemaster> charge = new List<tblchargemaster>();
charge = charge.AddRange(
ObjDB.SelectQuert("tblchargemaster").Cast<tblchargemaster>());