榕树下。。。

在成功的道路上,你没有耐心去等待成功的到来,那么,你只好用一生的耐心去面对失败
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

net2005中将list<>数组转换为Table

Posted on 2007-11-16 16:51  农村的芬芳  阅读(606)  评论(0编辑  收藏  举报

 public static DataTable GetDataTableFromIList<T>(List<T> aIList)
        {

            DataTable _returnTable = new DataTable();

            if (aIList.Count > 0)
            {

                //Creates the table structure looping in the in the first element of the list

                object _baseObj = aIList[0];

                Type objectType = _baseObj.GetType();

                PropertyInfo[] properties = objectType.GetProperties();

                DataColumn _col;

                foreach (PropertyInfo property in properties)
                {

                    _col = new DataColumn();

                    _col.ColumnName = (string)property.Name;

                    _col.DataType = property.PropertyType;

                    _returnTable.Columns.Add(_col);

                }

                //Adds the rows to the table

                DataRow _row;

                foreach (object objItem in aIList)
                {

                    _row = _returnTable.NewRow();

                    foreach (PropertyInfo property in properties)
                    {
                        _row[property.Name] = property.GetValue(objItem, null);
                    }
                    _returnTable.Rows.Add(_row);

                }

            }

            return _returnTable;

        }