• C#从入门到放弃--DataTable和List互转


    public class DtToList<T> where T : new()  
        {
            /// <summary>
            /// datatable转list
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static  List<T> ConvertToModel(DataTable dt)
            {
    
                List<T> ts = new List<T>();// 定义集合
                Type type = typeof(T); // 获得此模型的类型
                string tempName = "";
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!pi.CanWrite) continue;
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
        }
    datatable转list
    DataTable转List
    /// <summary>
            /// list转datatable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="collection"></param>
            /// <returns></returns>
            public  DataTable  ListToDt<T>(IEnumerable<T> collection)
            {
                var props = typeof(T).GetProperties();
                var dt = new DataTable();
                dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
                if (collection.Count() > 0)
                {
                    for (int i = 0; i < collection.Count(); i++)
                    {
                        ArrayList tempList = new ArrayList();
                        foreach (PropertyInfo pi in props)
                        {
                            object obj = pi.GetValue(collection.ElementAt(i), null);
                            tempList.Add(obj);
                        }
                        object[] array = tempList.ToArray();
                        dt.LoadDataRow(array, true);
                    }
                }
                return dt;
            }
    list转datatable
    List转Datable

     附1:上述为反射的方式,还可以采用序列化-反序列化的方式

     Student newSt = JsonConvert.DeserializeObject<Student >(JsonConvert.SerializeObject(oldSt ));

    附2:参考文献

    反射部分参考:DataTable和List互转

  • 相关阅读:
    :where()和:is()
    响应式布局(媒体查询+rem)
    v-html的问题及解决办法
    Sticky Footer(粘性页脚)
    css多行文字垂直居中
    BFC
    margin负值的情况
    windows系统设置环境变量
    hash和history原生事件
    腾讯WeTest零售行业质量解决方案
  • 原文地址:https://www.cnblogs.com/xuhp/p/13345097.html
Copyright © 2020-2023  润新知