【问题标题】:How do I quickly convert DataTable to IList<myType>如何快速将 DataTable 转换为 IList<myType>
【发布时间】:2018-03-04 00:46:13
【问题描述】:

在我的示例中,我尝试使用给定的项目源查看网格控件中的关键信息。在这种情况下,要传递项目源,我需要在 C# 中将 DataTable 转换为 IList&lt;myType&gt;

我已经尝试了所有传统的转换方法,包括下面的代码将DataTable转换为IList

dt.AsEnumerable().Cast<object>().ToList()

但是所有传统方法对我没有帮助,因为我不知道在DataTable 的各个列中使用了哪些对象以及它们的类型。 DataTable 也有更多的列和行。

例如,我的数据表中有以下列值。

PlanRowPID,PlanRowClass,PlanRowVendor,PlanRowColor
PID 0,CLASS 8,VENDOR A,COLOR D
PID 1,CLASS 7,VENDOR B,COLOR C
PID 2,CLASS 9,VENDOR C,COLOR B
PID 3,CLASS 6,VENDOR D,COLOR B

最后我想以编程方式执行以下操作,

IList<myType> list = new IList<myType>;
list.Add(new myType() {PlanRowPID = "PID 0",PlanRowClass = "CLASS 8",PlanRowVendor = "VENDOR A",PlanRowColor=COLOR D});
list.Add(new myType() {PlanRowPID = "PID 1",PlanRowClass = "CLASS 7",PlanRowVendor = "VENDOR B",PlanRowColor=COLOR C});
list.Add(new myType() {PlanRowPID = "PID 2",PlanRowClass = "CLASS 9",PlanRowVendor = "VENDOR C",PlanRowColor=COLOR B});

在我的应用程序中,我有超过 10000 个数据列,因此无法将数据表中的每个对象都添加到列表中。我需要花费更多的时间和知识来查找 @ 中可用的每个列的数据类型987654331@,然后根据 myType 类的类型创建属性。

所以请提供任何最佳和最快的方法将DataTable 转换为IList&lt;myType&gt;

【问题讨论】:

  • 您是否尝试过使用像实体框架这样的 ORM?
  • 是的,但 ORM 仅在我的实体数量较少时才有用。如果我有更多实体,则很难通过查找每列的数据类型来创建类。我需要编程的方式来查找类型并有效地创建类。
  • 您能告诉我们为什么您有 10,000 列吗?

标签: c# wpf list datatable ienumerable


【解决方案1】:

请尝试,

private static List<T> ConvertDataTable<T>(DataTable dt)  
{  
    List<T> data = new List<T>();  
    foreach (DataRow row in dt.Rows)  
    {  
        T item = GetItem<T>(row);  
        data.Add(item);  
    }  
    return data;  
} 

private static T GetItem<T>(DataRow dr)  
{  
    Type temp = typeof(T);  
    T obj = Activator.CreateInstance<T>();  

    foreach (DataColumn column in dr.Table.Columns)  
    {  
        foreach (PropertyInfo pro in temp.GetProperties())  
        {  
            if (pro.Name == column.ColumnName)  
                pro.SetValue(obj, dr[column.ColumnName], null);  
            else  
                continue;  
        }  
    }  
    return obj;  
}

调用示例,

List<Student> studentDetails = new List<Student>();  
studentDetails = ConvertDataTable<Student>(dt);  

来源:-http://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/

【讨论】:

  • 谢谢。但我的实际问题是,如何通过初始化从每个数据表行获得的属性来定义“学生”类。是否存在任何编程方式来定义类并初始化数据表中可用的属性?对于我的示例,我需要以编程方式使用“PlanRowPID”、“PlanRowClass”等创建类“Plan”。
【解决方案2】:

在这种情况下,要传递项目源,我需要在 C# 中将 DataTable 转换为 IList

您不能将ItemsSource 属性设置为DataTableDefaultView 吗?

dataGrid.ItemsSource = dt.DefaultView;

那么就不用转成列表了。

DataView 实现 IList

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多