zoukankan      html  css  js  c++  java
  • 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; }
        }
  • 相关阅读:
    淘宝技术架构演进之路
    单点登录
    [c++11] ——条件变量(Condition Variable)
    std::lock_guard unique_lock
    C++中push_back和emplace_back的区别
    C++11 CAS无锁函数compare_exchange_weak的使用
    C++11新特性之 rvalue Reference(右值引用)
    C++ auto和decltype的区别
    ovs contrack
    周总结03
  • 原文地址:https://www.cnblogs.com/T-FQlin/p/5795119.html
Copyright © 2011-2022 走看看