DataTableToList

 很简单的转换功能,这是我在GitHub上复制的一段代码(懒得再去找原地址了),感觉功能还算可以,贴出来分享给大家

        /// <summary>
        /// DataTable to List converter generic class.
        /// Convert DataTable to a specific class List<>.
        /// The Class Property Name must be same as the Column Name of the DataTable.
        /// The mapping is directly upon "Class Property Name" and "Column Name of the DataTable".
        /// </summary>
        public static List<T> ConvertDataTableToList<T>(DataTable table)
            where T : class, new()
        {
            List<Tuple<DataColumn, PropertyInfo>> map =
                new List<Tuple<DataColumn, PropertyInfo>>();

            foreach (PropertyInfo pi in typeof(T).GetProperties())
            {
                //ColumnAttribute col = (ColumnAttribute)
                //    Attribute.GetCustomAttribute(pi, typeof(ColumnAttribute));
                //if (col == null) continue;
                if (table.Columns.Contains(pi.Name))
                {
                    map.Add(new Tuple<DataColumn, PropertyInfo>(
                        table.Columns[pi.Name], pi));
                }
            }

            List<T> list = new List<T>(table.Rows.Count);
            foreach (DataRow row in table.Rows)
            {
                if (row == null)
                {
                    list.Add(null);
                    continue;
                }
                T item = new T();
                foreach (Tuple<DataColumn, PropertyInfo> pair in map)
                {
                    object value = row[pair.Value1];
                    if (value is DBNull) value = null;
                    pair.Value2.SetValue(item, value, null);
                }
                list.Add(item);
            }
            return list;
        }

 

sealed class Tuple<T1, T2>
    {
        public Tuple() { }
        public Tuple(T1 value1, T2 value2) { Value1 = value1; Value2 = value2; }
        public T1 Value1 { get; set; }
        public T2 Value2 { get; set; }
    }

 

posted @ 2016-08-22 12:12  T林飘叶  阅读(920)  评论(0编辑  收藏  举报