Updated on Kisan Patel
The following are the static functions in which if we pass a any type of Generic List as data source and it will convert it to DataTable
type.
public static class Utils { public static DataTable ToDataTable<TSource>(this IList<TSource> data) { DataTable dataTable = new DataTable(typeof(TSource).Name); PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach (TSource item in data) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } dataTable.Rows.Add(values); } return dataTable; } }
Now, use above static method to convert generic list to datatable as mentioned in below:
//Query data and store into variable... Listusers = context.Users.ToList(); //Convert it to DataTable DataTable dt = dt.ToDataTable<User>();