I'm trying to convert string collection type to dictionary that contain various types of keys and values(the value will be a struct most of the time. each string in the string collection will contain the key in the first element and the rest of the string will contain the struct elements(The Values of the Dictionary), of course that the string will contain the right type of each element in the struct we just need to decode the struct elements' type... i tried to do so but i ran into dead end and no possibility... i tried to google it but my case is pretty hard because it suppose to match to a lot of cases in my program... this is what i tried to do
private static void LoadDictionaryFromString<TKey,TValue>(ref IDictionary<TKey,TValue> argetDict,StringCollection SourceString)
{
TargetDict.Clear();
foreach(string strData in SourceString)
{
string[] strElements = strData.Split(';');
int m = 1;
// i must initialize
object Key = new object(); // when i try => TKey Key = new TKey() it's not working
object Value = new object(); // the same like previous line...
foreach (var field in typeof(TValue).GetFields())
{
// I can't work this out.... i stuck here
// in this line i'm getting an exception -> out of index...
TypeDescriptor.GetProperties(TargetDict.Values)[m].SetValue(Value , strElements[m]);
}
TypeDescriptor.GetProperties(TargetDict.Keys)[0].SetValue(Key, strElements[0]);
TargetDict.Add((TKey)Key,(TValue)Value);
}
}
I hope some one can help me with this because I struggled with this a lot.
Thanks
I'm adding a sample for the input of the string collection, the string collection has been saved before from the same dictionary, so let's say the current dictionary contains the key and value like this: , the key is the OrderID the sample struct contain the fields:
struct sampleStruct
{
string StockName;
int Quantity;
int StockType;
enum_Status StockStatus; // the declaration: enum enum_Status { Accepted, Cancel, Executed }
double Price;
DateTime TradeTime;
}
now let's say we have two records that contain the values:
OrderID = 155 (for the key part) and for the struct : Apple , 200, 1, Accepted, 250, 12/05/2013 10:00:00
OrderID = 156 (for the key part) and for the struct : IBM, 105, 1, Executed, 200, 12/05/2013 12:34:10
so the saved string collection will be name StringCollection strCollection;
"155;Apple;200;1;Accepted;250;12/05/2013 10:00:00
156;IBM;105;1;Executed;200;12/05/2013 12:34:10"
now, after a while i have a saved string collection from the kind above and i know that it contains the specified struct above so i run the function like this:
IDictionary<int, sampleStruct> DictToTarget=new IDictionary<int, sampleStruct>();
// the Dictionary will be cleared and will contain the data as saved in the string collection
// the stringCollection will contain the data above
LoadDictionaryFromString<int, sampleStruct>(ref DictToTarget, strCollection);
I hope that's enough data to help me. Thanks again.