Using Reflection to create a DataTable from a Class?

后端 未结 9 2006
星月不相逢
星月不相逢 2020-12-02 07:39

I\'ve just learned about Generics and I\'m wondering whether I can use it to dynamically build datatables from my classes.

Or I might be missing the point here. Here

9条回答
  •  广开言路
    2020-12-02 08:17

    Here is a more compact version of David's answer that is also an extension function. I've posted the code in a C# project on Github.

    public static class Extensions
    {
        public static DataTable ToDataTable(this IEnumerable self)
        {
            var properties = typeof(T).GetProperties();
    
            var dataTable = new DataTable();
            foreach (var info in properties)
                dataTable.Columns.Add(info.Name, Nullable.GetUnderlyingType(info.PropertyType) 
                   ?? info.PropertyType);
    
            foreach (var entity in self)
                dataTable.Rows.Add(properties.Select(p => p.GetValue(entity)).ToArray());
    
            return dataTable;
        }     
    }
    

    I have found that this works very well in conjunction with code to write a DataTable to CSV.

提交回复
热议问题