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;
        }

你可能感兴趣的:(reflection)