我正在嘗試從我的DataTable創建一個字典。目前我通過首先創建一個IList,然後循環遍歷列表並將它們添加到單獨的字典中,逐個指定列表中的結果對象的主鍵屬性。使用泛型和擴展方法將數據錶轉換爲字典<T1,T2>
我想知道這是否可以使用泛型。
香港專業教育學院目前得到了下面的代碼,這犯規編譯或工作:
public static IDictionary<T1, T2> ToDictionary<T1,T2>(this DataTable table) where T2 : new()
{
IList<PropertyInfo> properties = GetPropertiesForType<T2>();
IDictionary<T1,T2> result = new Dictionary<T1,T2>();
Dictionary<string, int> propDict = GetPropertyDictionary(properties, table);
T1 PK;
foreach (var row in table.Rows)
{
var item = CreateDictItemFromRow<T2>((DataRow)row, properties, propDict);
result.Add(item. item); //not sure here
}
return result;
}
基本上我想調用如下
Dictionary<int, MyDBClass> Items = DataTable.ToDictionary<int,MyDBClass>();
或
Dictionary<Int16,MyDBClass> Items = DataTable.ToDictionary<Int16, MyDBClass>();
林假設某處我需要將主鍵屬性名稱傳遞給此函數。否則,我可以安全地假設我的Datatable中的第一列包含主鍵(儘管假設它始終是一個int(它可能是一個短字節或字節))並不安全。
我也明白這可以很容易地使用LINQ完成,但我沒有得到那麼遠的C#,並希望改變現有的應用程序。
幫助表示讚賞。
有一個與你問什麼,怎麼會是可能的,如果數據表有更多問題比兩列? – IamStalker 2012-02-16 05:39:13
MyDBClass是一個包含所有列信息作爲屬性的類。我可以把它當作列表,但是我隨後將它們手動添加到字典中。我只想泛化這個 –
Simon
2012-02-16 05:43:33