Conversion Between DataTable and List in C#
Introduction
Sometimes in projects we may face a situation where we have to convert:
Now rather than making custom conversion mechanism of each different user defined type, let’s make generic converters to save code and time.
List to DataTable
Here is the extension method to convert a List to a DataTable:
DataTable to List<TSource>
Introduction
Sometimes in projects we may face a situation where we have to convert:
- A IList of user defined type to a DataTable or
- A DataTable to a List of user defined type
Now rather than making custom conversion mechanism of each different user defined type, let’s make generic converters to save code and time.
List to DataTable
Here is the extension method to convert a List to a DataTable:
////// Convert Genric List to DataTable /// public static DataTable ToDataTable(this IList listObject) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable myTable = new DataTable(); foreach (PropertyDescriptor prop in properties) { myTable.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[properties.Count]; foreach (T item in listObject) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } myTable.Rows.Add(values); } return myTable; }
DataTable to List<TSource>
////// Convert DataTable to Genric List /// public static ListDataTableMapToList (DataTable dtSource) { string propName = string.Empty; List entityList = new List (); foreach (DataRow dr in dtSource.Rows) { // Create Instance of the Type T T entity = Activator.CreateInstance (); // Get all properties of the Type T System.Reflection.PropertyInfo[] entityProperties = typeof(T).GetProperties(); // Loop through the properties defined in the // entityList entity object and mapped the value foreach (System.Reflection.PropertyInfo item in entityProperties) { propName = string.Empty; if (propName.Equals(string.Empty)) propName = item.Name; if (dtSource.Columns.Contains(propName)) { // Assign value to the property item.SetValue ( entity, dr[propName].GetType().Name.Equals(typeof(DBNull).Name) ? null : dr[propName], null ); } } entityList.Add(entity); } return entityList; }
No comments:
Post a Comment