There is no built in method for converting list to data table in C#.
So we can implement following method for converting List to DataTable in C#.
public DataTable ToDataTable<T>(IList<T> data)// T is any generic type { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; }
|
abc cdedPosted Oct 25, 2017, 4:57 AM
What if my class which is generic is complex which has objects inside objects ?
Mahesh kumawatPosted May 23, 2015, 1:35 AM
I try like this DataTable dt = new DataTable(); dt = (DataTable)ToDataTable(lst);
Mahesh kumawatPosted May 23, 2015, 1:34 AM
How to call this function ....(ToDataTable)
VEERENDRA kUMARPosted Oct 14, 2014, 8:22 PM
thank u.
siva kumarPosted Jul 3, 2013, 4:52 AM
exact solution worked for me.
Muhannad MagladPosted Sep 11, 2012, 3:59 AM
thank you man
Muhannad MagladPosted Sep 11, 2012, 3:59 AM
thank you man