reflection

public static DataTable LinqToDataTable(System.Collections.IEnumerable list)
        {
            DataTable table = new DataTable();
            bool schemaIsBuild = false;
            PropertyInfo[] props = null;
            foreach (object item in list)
            {
                if (!schemaIsBuild)
                {
                    props = item.GetType().GetProperties();
                    foreach (var pi in props)
                    {
                        table.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
                        schemaIsBuild = true;
                    }
                    var row = table.NewRow();
                    foreach (var pi in props)
                        row[pi.Name] = pi.GetValue(item, null);
                    table.Rows.Add(row);
                }
            }
            table.AcceptChanges();
            return table;
        }

posted on 2010-05-08 08:42  Gsun  阅读(160)  评论(0编辑  收藏  举报

导航