Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<dynamic> to List<OurClass> in c#

Tags:

c#

asp.net

I create a dynamic list at run-time and after execution I need to assign the list to my class properties

List<tblchargemaster> charge = new List<tblchargemaster>();

charge = (List<tblchargemaster>) ObjDB.SelectQuery("tblchargemaster");

tblchargemaster is the class type and SelectQuery function returns List<dynamic>. How can I convert this dynamic list to a list with my class type?

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

And Generic Class is

    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;
    }
}
like image 600
Dinesh Avatar asked May 13 '14 10:05

Dinesh


2 Answers

Edited, since explicit cast from dynamic to a strong type is not supported.

var charge = ObjDB.SelectQuert("tblchargemaster").Cast<tblchargemaster>();

becomes:

var charge = ObjDB.SelectQuert("tblchargemaster").Select(CastDynamicTo<tblchargemaster>)

whereas CastDynamicTo<tblchargemaster> is implemented by help of Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?

like image 192
chiccodoro Avatar answered Sep 18 '22 14:09

chiccodoro


Use Cast<tblchargemaster>() method:

List<tblchargemaster> charge = new List<tblchargemaster>();

charge = charge.AddRange(
   ObjDB.SelectQuert("tblchargemaster").Cast<tblchargemaster>());
like image 29
Vladimir Sachek Avatar answered Sep 19 '22 14:09

Vladimir Sachek