fyf

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

List 转换 DataTable DataSet的方法

Posted on 2010-03-25 10:41  fyf  阅读(224)  评论(0)    收藏  举报

 /// <summary>
        /// List转换成DataSet
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="list">将要转换的List</param>
        /// <returns></returns>
        public DataSet ConvertToDataSet<T>(IList<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;

        }

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wangygang/archive/2009/09/07/4527613.aspx