如何快速将DataTable转换为IList <mytype>

时间:2017-09-22 12:21:10

标签: c# wpf list datatable ienumerable

在我的示例中,我尝试使用给定的项目源查看网格控件中的关键信息。在这种情况下,为了传递项目来源,我需要在C#中将IList<myType>转换为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});

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

DataTable

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

因此,请提供将DataTable转换为IList<myType>的最佳和最快捷方式。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

  

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

您是否只能将ItemsSource属性设置为DefaultView的{​​{1}}?

DataTable

然后无需将其转换为列表。

dataGrid.ItemsSource = dt.DefaultView; 实施DataView