1. 程式人生 > >C#之DataTable轉List與List轉Datatable

C#之DataTable轉List與List轉Datatable

!= get mod 通過 summary wro turn eof lis

閑來無事,只有寫代碼啦,以下為DataTable轉List與List轉DataTable的兩個方法,主要技術點用到了反射原理:

    /// <summary>
    /// 模型轉換類
    /// </summary>
    public class ConvertModel
    {
        /// <summary>
        /// DataTable轉List
        /// </summary>
        /// <typeparam name="T">list中的類型</typeparam>
        /// <param name="dt">
要轉換的DataTable</param> /// <returns></returns> public static List<T> DatatTableToList<T>(DataTable dt) where T : class, new() { List<T> list = new List<T>(); T t = new T(); PropertyInfo[] prop = t.GetType().GetProperties();
//遍歷所有DataTable的行 foreach (DataRow dr in dt.Rows) { t = new T(); //通過反射獲取T類型的所有成員 foreach (PropertyInfo pi in prop) { //DataTable列名=屬性名 if (dt.Columns.Contains(pi.Name)) {
//屬性值不為空 if (dr[pi.Name] != DBNull.Value) { object value = Convert.ChangeType(dr[pi.Name], pi.PropertyType); //給T類型字段賦值 pi.SetValue(t, value, null); } } } //將T類型添加到集合list list.Add(t); } return list; } /// <summary> /// List轉換為DataTable /// </summary> /// <typeparam name="T">List中的類型</typeparam> /// <param name="list">要轉換的list</param> /// <returns></returns> public static DataTable ListToDataTable<T>(List<T> list) where T : class { DataTable dt = new DataTable(); PropertyInfo[] prop = typeof(T).GetProperties(); DataColumn[] ColumnArr = prop.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray(); dt.Columns.AddRange(ColumnArr); foreach (T t in list) { DataRow dr = dt.NewRow(); foreach (PropertyInfo pi in prop) { if (dt.Columns.Contains(pi.Name)) { if (pi.GetValue(t) != null) { dr[pi.Name] = pi.GetValue(t); } } } dt.Rows.Add(dr); } return dt; } }

調用:

            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Sex");
            dt.Columns.Add("Age");
            dt.Columns.Add("Height");
            DataRow dr = dt.NewRow();
            dr["Id"] = 1;
            dr["Sex"] = 1;
            dr["Age"] = 18;
            dr["Height"] = 190;
            dt.Rows.Add(dr);
            //將DataTable轉換為List<Persion>
            List<Persion> list1 = ConvertModel.DatatTableToList<Persion>(dt);


            List<Persion> list = new List<Persion>()
            {
                new Persion(){Id=1,Sex=1,Age=26,Height=168},
                new Persion(){Id=2,Sex=0,Age=26,Height=168},
            };
            //將List<Persion>轉換為DataTable
            DataTable dt1 = ConvertModel.ListToDataTable<Persion>(list);

C#之DataTable轉List與List轉Datatable