美文网首页
C#DataTable与List互相转化

C#DataTable与List互相转化

作者: 多1份努力 | 来源:发表于2018-09-01 09:53 被阅读0次
public class Util
    {
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T>DtToList<T>(DataTable dt)
        {
            List<T> list = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T t = Activator.CreateInstance<T>();
                PropertyInfo[] properties = t.GetType().GetProperties();
                foreach (var item in properties)
                {
                    if (dt.Columns.Contains(item.Name))
                    {
                        object value = dr[item.Name];
                        if (value.ToString()!="")
                        {
                            item.SetValue(t,value.ToString(),null);
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }
        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(List<T> list)  {
            DataTable dt=new DataTable();
            Type type = typeof(T);
            List<PropertyInfo> properties = new List<PropertyInfo>();
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => {
                properties.Add(p);
                dt.Columns.Add(p.Name,p.PropertyType);
            });
            foreach (var item in list)
            {
                DataRow row = dt.NewRow();
                properties.ForEach(p => {
                    row[p.Name] = p.GetValue(item,null);
                });
                dt.Rows.Add(row);
            }
            return dt;
        }
    }

相关文章

网友评论

      本文标题:C#DataTable与List互相转化

      本文链接:https://www.haomeiwen.com/subject/txvywftx.html