please leave a comment so that i know what not to write about


Friday, April 13, 2012

Dynaminism in .Net 4.0

few dayz ago came across THIS question.
the solution to this can easily be figured out by the new dynamic features introduced in .Net 4.0.
i have made a project to demonstrate this.
the main code in the project goes like this

public static dynamic[] GetDynamicObject(DataTable dt, Dictionary<stringstring> mapping)
            List<dynamic> returnList = new List<dynamic>();
            foreach (DataRow row in dt.Rows)
                dynamic obj = new ExpandoObject();
                var objectDic = (IDictionary<stringobject>)obj;
                foreach (DataColumn column in dt.Columns)
                    objectDic.Add(mapping!=null?mapping.ContainsKey(column.ColumnName) ? mapping[column.ColumnName] : column.ColumnName:column.ColumnName,row[column]);
            return returnList.ToArray();
The static method here named "GetDynamicObject" simply takes a data table(which can be populated by the data in the database) and a dictionary of <string,object> as the mapping. 
then for each row in the DataTable the method makes a dynamic Object of type ExpandoObject which was introduced for the sole purpose of adding and consuming the propertiese at runtime. more info about expando object can be got from here(MSDN link).

The full project i made is available here(Sky Drive link).
There was an error in this gadget