[英]Convert Dictionary<MyType>.ValueCollection to IList<MyType>
[英]How do I quickly convert DataTable to IList<myType>
在我的示例中,我嘗試查看具有給定項源的Grid控件中的關鍵信息。 在這種情況下,要傳遞項目源,我需要將DataTable
轉換為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});
在我的應用程序中,我有超過10000個數據列,因此不可能將數據表中的每個對象都添加到列表中。我需要花費更多的時間和知識來查找DataTable
可用的每個列的數據類型,然后創建屬性基於myType
類的類型。
因此,請提供任何最佳,最快的方法將DataTable
轉換為IList<myType>
。
請試試,
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/
在這種情況下,要傳遞項目源,我需要將
DataTable
轉換為C#中的IList
。
您不能僅將ItemsSource
屬性設置為DataTable
的DefaultView
嗎?
dataGrid.ItemsSource = dt.DefaultView;
然后,無需將其轉換為列表。
DataView
實現IList
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.