码迷,mamicode.com
首页 > 其他好文 > 详细

c#将List<T>转换成DataSet

时间:2014-06-13 20:34:53      阅读:733      评论:0      收藏:0      [点我收藏+]

标签:c#将listt转换成dataset   c#   dataset   

        /// <summary>
        /// List<T> 转换成DataSet
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="list">集合</param>
        /// <returns>DataSet</returns>
        public static DataSet ConvertToDataSet<T>(List<T> list)
        {
            if (list == null || list.Count <= 0)
            {
                return null;
            }

            DataSet ds = new DataSet();
            DataTable dt = new DataTable(typeof(T).Name);
            DataColumn column;
            DataRow row;

            System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            foreach (T t in list)
            {
                if (t == null)
                {
                    continue;
                }

                row = dt.NewRow();

                for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    System.Reflection.PropertyInfo pi = myPropertyInfo[i];

                    string name = pi.Name;

                    if (dt.Columns[name] == null)
                    {
                        column = new DataColumn(name, pi.PropertyType);
                        dt.Columns.Add(column);
                    }

                    row[name] = pi.GetValue(t, null);
                }

                dt.Rows.Add(row);
            }
            ds.Tables.Add(dt);
            return ds;
        }
    }

c#将List<T>转换成DataSet,布布扣,bubuko.com

c#将List<T>转换成DataSet

标签:c#将listt转换成dataset   c#   dataset   

原文地址:http://blog.csdn.net/y_f123/article/details/30485401

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!