using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; namespace Common.Helper { public static class Mapper { public static IList DataTableToClass(DataTable Table) where T : class, new() { var dataList = new List(Table.Rows.Count); Type classType = typeof(T); IList propertyList = classType.GetProperties(); if (propertyList.Count == 0) return new List(); List columnNames = Table.Columns.Cast().Select(column => column.ColumnName.ToLower()).ToList(); try { foreach (DataRow dataRow in Table.AsEnumerable().ToList()) { var classObject = new T(); foreach (PropertyInfo property in propertyList) { if (property != null && property.CanWrite) { if (columnNames.Contains(property.Name.ToLower())) { if (dataRow[property.Name] != System.DBNull.Value) { object propertyValue = System.Convert.ChangeType( dataRow[property.Name], property.PropertyType ); property.SetValue(classObject, propertyValue, null); } } } } dataList.Add(classObject); } return dataList; } catch { return new List(); } } public static T DataRowToClass(DataRow row) where T : class, new() { Type classType = typeof(T); IList propertyList = classType.GetProperties(); if (propertyList.Count == 0) return new T(); List columnNames = row.Table.Columns.Cast().Select(column => column.ColumnName.ToLower()).ToList(); try { var classObject = new T(); foreach (PropertyInfo property in propertyList) { if (property != null && property.CanWrite) { if (columnNames.Contains(property.Name.ToLower())) { if (row[property.Name] != System.DBNull.Value) { object propertyValue = System.Convert.ChangeType( row[property.Name], property.PropertyType ); property.SetValue(classObject, propertyValue, null); } } } } return classObject; } catch { return new T(); } } } }