Linq 结果转换为DataTable

         /// <summary>
         ///
         /// </summary>
         /// <param name="list"></param>
         /// <returns></returns>
        private System.Data.DataTable GetDataTable(IEnumerable list)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            bool schemaIsBuild = false;
            PropertyInfo[] props = null;

            foreach (object item in list)
            {
                if (!schemaIsBuild)
                {
                    props = item.GetType().GetProperties();
                    foreach (var pi in props)
                        dt.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
                }

                schemaIsBuild = true;

                var row = dt.NewRow();
                foreach (var pi in props)
                {
                    row[pi.Name] = pi.GetValue(item, null);
                }
                dt.Rows.Add(row);
                dt.AcceptChanges();
            }
            return dt;
        }

posted @ 2011-11-23 11:22  wangjj89621  阅读(839)  评论(2编辑  收藏  举报