using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Reflection; using System.Text; namespace Nirvana.Common { public static class DataTableListHelper { /// /// DataTable 转换成泛型List /// /// 实体对象类 /// 数据DatatTable /// List<实体对象> public static List ToList(this DataTable table) { if (table == null) { return null; } List list = new List(); T t = default(T); PropertyInfo[] propertypes = null; string tempName = string.Empty; foreach (DataRow row in table.Rows) { t = Activator.CreateInstance(); propertypes = t.GetType().GetProperties(); foreach (PropertyInfo pro in propertypes) { if (!pro.CanWrite) { continue; } tempName = pro.Name; if (table.Columns.Contains(tempName.ToUpper())) { object value = row[tempName]; if (value is System.DBNull) { value = null; if (pro.PropertyType.FullName == "System.String") { value = string.Empty; } } if (pro.PropertyType.IsGenericType && pro.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && value != null) { pro.SetValue(t, Convert.ChangeType(value, Nullable.GetUnderlyingType(pro.PropertyType)), null); } else if (pro.PropertyType.IsEnum) { pro.SetValue(t, Convert.ChangeType(value, Enum.GetUnderlyingType(pro.PropertyType)), null); } else if (pro.PropertyType.FullName == "System.Guid") { pro.SetValue(t, new Guid(value + ""), null); } else if(pro.PropertyType.FullName == "System.Decimal") { pro.SetValue(t, Convert.ToDecimal(value), null); } else if(pro.PropertyType.FullName == "System.Int32") { pro.SetValue(t, Convert.ToInt32(value), null); } else { pro.SetValue(t, value, null); } } } list.Add(t); } return list; } /// /// 将List转换成DataTable /// /// /// /// public static DataTable ToDataTable(this IList data) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dt = new DataTable(); for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; if (property.PropertyType.Name != typeof(Nullable<>).Name) { dt.Columns.Add(property.Name, property.PropertyType); } else { dt.Columns.Add(property.Name, property.PropertyType.GenericTypeArguments[0]); } } object[] values = new object[properties.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } dt.Rows.Add(values); } return dt; } } }