使用反射从类创建数据表

本文关键字:创建 数据表 反射 | 更新日期: 2023-09-27 18:31:01

我刚刚了解了泛型,我想知道我是否可以使用它从我的类动态构建数据表。

或者我可能错过了这里的重点。这是我的代码,我正在尝试做的是从我现有的类创建一个数据表并填充它。 然而,我陷入了思考过程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
namespace Generics
{
    public class Dog
    {
        public string Breed { get; set; }
        public string Name { get; set; }
        public int legs { get; set; }
        public bool tail { get; set; }
    }
    class Program
    {
        public static DataTable CreateDataTable(Type animaltype)
        {
            DataTable return_Datatable = new DataTable();
            foreach (PropertyInfo info in animaltype.GetProperties())
            {
                return_Datatable.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            return return_Datatable;
        }
        static void Main(string[] args)
        {
            Dog Killer = new Dog();
            Killer.Breed = "Maltese Poodle";
            Killer.legs = 3;
            Killer.tail = false;
            Killer.Name = "Killer";
            DataTable dogTable = new DataTable();
            dogTable = CreateDataTable(Dog);
//How do I continue from here?

        }      
    }
}    

现在在DataTable点它出错了。另外,作为反射和泛型的新手,我将如何使用 Killer 类实际填充数据?

使用反射从类创建数据表

基于前面的所有答案,下面是一个从任何集合创建 DataTable 的版本:

public static DataTable CreateDataTable<T>(IEnumerable<T> list)
{
    Type type = typeof(T);
    var properties = type.GetProperties();      
    
    DataTable dataTable = new DataTable();
    dataTable.TableName = typeof(T).FullName;
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }
    
    foreach (T entity in list)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }
        
        dataTable.Rows.Add(values);
    }
    
    return dataTable;
}

这是David答案的更紧凑版本,也是一个扩展函数。我已经在 Github 上的 C# 项目中发布了代码。

public static class Extensions
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> 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;
    }     
}

我发现这与将 DataTable 写入 CSV 的代码结合使用效果很好。

我最喜欢的自制函数。 它同时创建和填充所有内容。 扔任何物体。

 public static DataTable ObjectToData(object o)
 {
    DataTable dt = new DataTable("OutputData");
    DataRow dr = dt.NewRow();
    dt.Rows.Add(dr);
    o.GetType().GetProperties().ToList().ForEach(f =>
    {
        try
        {
            f.GetValue(o, null);
            dt.Columns.Add(f.Name, f.PropertyType);
            dt.Rows[0][f.Name] = f.GetValue(o, null);
        }
        catch { }
    });
    return dt;
 }

可以通过更改以下内容来解决此错误:

dogTable = CreateDataTable(Dog);

对此:

dogTable = CreateDataTable(typeof(Dog));

但是,对于您要做的事情,有一些注意事项。首先,DataTable不能存储复杂类型,因此,如果Dog上有Cat实例,则无法将其添加为列。在这种情况下,你想做什么取决于你,但请记住这一点。

其次,我建议你唯一使用DataTable的时候是当你构建的代码时,它对它所消耗的数据一无所知。这有有效的用例(例如,用户驱动的数据挖掘工具)。如果您已经在Dog实例中拥有数据,只需使用它即可。

另一个小花絮,这个:

DataTable dogTable = new DataTable();
dogTable = CreateDataTable(Dog);

可以浓缩为:

DataTable dogTable = CreateDataTable(Dog);

下面是一些修改的代码,它修复了数据时间字段的时区问题:

    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection props =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                if (props[i].PropertyType == typeof(DateTime))
                {
                    DateTime currDT = (DateTime)props[i].GetValue(item);
                    values[i] = currDT.ToUniversalTime();
                }
                else
                {
                    values[i] = props[i].GetValue(item);
                }
            }
            table.Rows.Add(values);
        }
        return table;
    }

这是一个 VB.Net 版本,它从作为对象传递给函数的泛型列表创建数据表。还有一个帮助程序函数(ObjectToDataTable),它从对象创建数据表。

导入系统.反射

   Public Shared Function ListToDataTable(ByVal _List As Object) As DataTable
    Dim dt As New DataTable
    If _List.Count = 0 Then
        MsgBox("The list cannot be empty. This is a requirement of the ListToDataTable function.")
        Return dt
    End If
    Dim obj As Object = _List(0)
    dt = ObjectToDataTable(obj)
    Dim dr As DataRow = dt.NewRow
    For Each obj In _List
        dr = dt.NewRow
        For Each p as PropertyInfo In obj.GetType.GetProperties
            dr.Item(p.Name) = p.GetValue(obj, p.GetIndexParameters)
        Next
        dt.Rows.Add(dr)
    Next
    Return dt
End Function
Public Shared Function ObjectToDataTable(ByVal o As Object) As DataTable
    Dim dt As New DataTable
    Dim properties As List(Of PropertyInfo) = o.GetType.GetProperties.ToList()
    For Each prop As PropertyInfo In properties
        dt.Columns.Add(prop.Name, prop.PropertyType)
    Next
    dt.TableName = o.GetType.Name
    Return dt
End Function

使用 @neoistheone 提供的答案,我更改了以下部分。 现在工作正常。

DataTable dogTable = new DataTable();
        dogTable = CreateDataTable(typeof(Dog));
        dogTable.Rows.Add(Killer.Breed, Killer.Name,Killer.legs,Killer.tail);
        foreach (DataRow row in dogTable.Rows)
        {
            Console.WriteLine(row.Field<string>("Name") + " " + row.Field<string>("Breed"));
            Console.ReadLine();
        }

您可以将对象转换为XML,然后将XML文档加载到数据集,然后从数据集中提取第一个表。但是,我看不出这如何实用,因为它推断创建流,数据集和数据表并使用对话来创建xml文档。

我想为了证明概念,我可以理解为什么。这是一个示例,但对使用它有些犹豫。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Xml.Serialization;
namespace Generics
{
public class Dog
{
    public string Breed { get; set; }
    public string Name { get; set; }
    public int legs { get; set; }
    public bool tail { get; set; }
}
class Program
{
    public static DataTable CreateDataTable(Object[] arr)
    {
        XmlSerializer serializer = new XmlSerializer(arr.GetType());
        System.IO.StringWriter sw = new System.IO.StringWriter();
        serializer.Serialize(sw, arr);
        System.Data.DataSet ds = new System.Data.DataSet();
        System.Data.DataTable dt = new System.Data.DataTable();
        System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
        ds.ReadXml(reader);
        return ds.Tables[0];
    }
    static void Main(string[] args)
    {
        Dog Killer = new Dog();
        Killer.Breed = "Maltese Poodle";
        Killer.legs = 3;
        Killer.tail = false;
        Killer.Name = "Killer";
        Dog [] array_dog = new Dog[5];
        Dog [0] = killer;
        Dog [1] = killer;
        Dog [2] = killer;
        Dog [3] = killer;
        Dog [4] = killer;
        DataTable dogTable = new DataTable();
        dogTable = CreateDataTable(array_dog);
        // continue here
        }      
    }
}

在此处查看以下示例

如果要设置列顺序/仅包含某些列/排除某些列,请尝试以下操作:

        private static DataTable ConvertToDataTable<T>(IList<T> data, string[] fieldsToInclude = null,
string[] fieldsToExclude = null)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
        {
            if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
                (fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
                continue;
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
        foreach (T item in data)
        {
            var atLeastOnePropertyExists = false;
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
            {
                if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
(fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
                    continue;
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                atLeastOnePropertyExists = true;
            }
            if(atLeastOnePropertyExists) table.Rows.Add(row);
        }

        if (fieldsToInclude != null)
            SetColumnsOrder(table, fieldsToInclude);
        return table;
    }
    private static void SetColumnsOrder(DataTable table, params String[] columnNames)
    {
        int columnIndex = 0;
        foreach (var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }