c# - How to convert a list into data table -
this question has answer here:
- convert generic list/enumerable datatable? 17 answers
i have data list property. want convert list data data table. how convert list datable.
just add function , call it, convert list datatable.
public static datatable todatatable<t>(list<t> items) { datatable datatable = new datatable(typeof(t).name); //get properties propertyinfo[] props = typeof(t).getproperties(bindingflags.public | bindingflags.instance); foreach (propertyinfo prop in props) { //defining type of data column gives proper data table var type = (prop.propertytype.isgenerictype && prop.propertytype.getgenerictypedefinition() == typeof(nullable<>) ? nullable.getunderlyingtype(prop.propertytype) : prop.propertytype); //setting column names property names datatable.columns.add(prop.name, type); } foreach (t item in items) { var values = new object[props.length]; (int = 0; < props.length; i++) { //inserting property values datatable rows values[i] = props[i].getvalue(item, null); } datatable.rows.add(values); } //put breakpoint here , check datatable return datatable; }
Comments
Post a Comment