DataTable employeeDt = employeeList.ConvertToDataTable();
________________________________________________________________
- public static DataTable ConvertToDataTable<T>(List<T> list)
- {
- DataTable tempDt = new DataTable(typeof(T).Name);
- //return all properties
- var [] propInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
- foreach (var prop in propInfo)
- {
- //defining type
- var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
- //set the column name
- tempDt.Columns.Add(prop.Name, type);
- }
- foreach (var item in list)
- {
- var values = new object[propInfo.Length];
- for (int i = 0; i < propInfo.Length; i++)
- {
- //prepare for datatable
- values[i] = propInfo[i].GetValue(item, null);
- }
- tempDt .Rows.Add(values);
- }
- return dataTable;
- }
_______________________________________________________________________________________________
Convert from IEnumerable to datatable in C#
- public static DataTable ConvertToDataTable<T>(this IEnumerable<T> dataCollection)
- {
- PropertyDescriptorCollection propertiesDC =
- TypeDescriptor.GetProperties(typeof(T));
- DataTable dt = new DataTable();
- foreach (var item in propertiesDC)
- dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType);
- foreach (var row in dataCollection)
- {
- DataRow r = table.NewRow();
- foreach (var p in propertiesDC)
- r[p.Name] = p.GetValue(item) ?? DBNull.Value;
- table.Rows.Add(r);
- }
- return dt;
- }
Create dataTable in C#
- var myTable = new DataTable();
- myTable.Columns.Add("Id", typeof(int));
- myTable.Columns.Add("Name", typeof(string));
No comments:
Post a Comment