How to convert any generic type list to Data table?
In this article I am going to discuss how to convert any type of list to data table. Please check below code to convert the generic type to data table.
Here I am using the reflection to get the property-info & generate the data table columns & then filling the row values one by one in the data table.
public static DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); PropertyInfo[] propertyInfoArray = properties; for (int i = 0; i < (int)propertyInfoArray.Length; i++) { PropertyInfo propertyInfo = propertyInfoArray[i]; dataTable.Columns.Add(propertyInfo.Name); } foreach (T item in items) { object[] value = new object[(int)properties.Length]; for (int j = 0; j < (int)properties.Length; j++) { value[j] = properties[j].GetValue(item, null); } dataTable.Rows.Add(value); } return dataTable; }
Here I am using the reflection to get the property-info & generate the data table columns & then filling the row values one by one in the data table.
0 comments :
Post a Comment