版权保护声明:本文未经许可,禁止任何形式转载,违者必究。
刚才看到博客园的一个讨论,C# DataTable 转 List(大家进来讨论讨论) ,提供一个参考(http://stackoverflow.com/questions/1427484/convert-datatable-to-listt),具体实现和测试如下:
class Program { static void Main(string[] args) { Console.WriteLine("Start..."); Console.WriteLine("Add data to datatable..."); var dt = new DataTable(); dt.Columns.Add("Id", typeof(Int32)); dt.Columns.Add("Name", typeof(String)); dt.Columns.Add("Email", typeof(String)); dt.Columns.Add("Age", typeof(Int32)); for (int i = 1; i <= 5; i++) { var dr = dt.NewRow(); dr["Id"] = i; dr["Name"] = "Name " + i; dr["Email"] = "Eamil " + i; dr["Age"] = 20 + i; dt.Rows.Add(dr); } var list = ConvertTo<User>(dt); list.ForEach(x => { Console.WriteLine("Element==>>Id:{0},Name:{1},Email:{2},Age:{3}", x.Id, x.Name, x.Email, x.Age); }); Console.WriteLine("The end,press any key to exit..."); Console.ReadKey(); } public static List<T> ConvertTo<T>(DataTable dt) where T : new() { var list = new List<T>(); try { var columnNames = new List<string>(); foreach (DataColumn col in dt.Columns) { columnNames.Add(col.ColumnName); } PropertyInfo[] Properties; Properties = typeof(T).GetProperties(); list = dt.AsEnumerable().ToList().ConvertAll<T>(x => GetObject<T>(x, columnNames, Properties)); } catch { } return list; } public static T GetObject<T>(DataRow row, List<string> columnsName, PropertyInfo[] properties) where T : new() { T obj = new T(); try { string columnname = ""; string value = ""; foreach (PropertyInfo objProperty in properties) { columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); if (!string.IsNullOrEmpty(columnname)) { value = row[columnname].ToString(); if (!string.IsNullOrEmpty(value)) { if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) { value = row[columnname].ToString().Replace("$", "").Replace(",", ""); objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); } else { value = row[columnname].ToString().Replace("%", ""); objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null); } } } } return obj; } catch { return obj; } } } public class User { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public int Age { get; set; } }以上实现源自:http://stackoverflow.com/questions/1427484/convert-datatable-to-listt 谢谢博客园辉_辉的建议,将typeof(T).GetProperties()在GetObjct<T>()的外部来调用,这样可以避免每个DataRow都调用一次typeof(T).GetProperties()方法。 该实现还有需要优化的地方,仅供参考实现的思路。 最近更新的一篇关于DataTable转换成List<T>的文章:http://codedefault.com/2014/c-sharp-linq-convert-datatable-to-list
版权保护声明:本文未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册