I am attempting to create a Dictionary from my DataTable. Currently i do this by first creating a IList and then looping through the List and adding them to a dictionary individually specifying the Primary key property of the resulting object in the list on a case by case basis.
I was wondering if this could be done using generics.
Ive currently got the following code, which doesnt compile or work:
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;
}
Essentially i would like to call the following:
Dictionary<int, MyDBClass> Items = DataTable.ToDictionary<int,MyDBClass>();
or
Dictionary<Int16,MyDBClass> Items = DataTable.ToDictionary<Int16, MyDBClass>();
Im assuming somewhere i need to pass the primary key property name to this function. Failing that i can safely assume the first column in my Datatable contains the primary key (although its not safe to assume it is always an int (it maybe a short or byte)).
I also understand this could quite easily be done using LINQ, but i havent got that far in C# and wish to alter existing application.
Help is appreciated.
Hope this helps.
By the way, you need to include the assembly, System.Data.DataSetExtensions.dll, to use the Field extension method.
If you have any other questions, don’t hesitate to ask.