更新包含任何类型的各种键和结构的字典

时间:2013-05-12 11:46:45

标签: c# dictionary struct elements

我正在尝试将字符串集合类型转换为包含各种类型的键和值的字典(该值大多数时候都是结构体。 字符串集合中的每个字符串将包含第一个元素中的键,字符串的其余部分将包含struct元素(Dictionary的值),当然字符串将包含struct中每个元素的正确类型只需要解码struct elements的类型...... 我试图这样做,但我遇到了死胡同,没有可能...... 我试图谷歌它,但我的情况非常难,因为它假设与我的程序中的很多情况相匹配... 这就是我试图做的事情

     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);
        }
    }

我希望有人可以帮助我解决这个问题,因为我很努力地解决这个问题。

由于

我正在为字符串集合的输入添加一个示例, 字符串集合之前已保存在同一个字典中, 所以让我们说当前字典包含这样的键和值:  , 关键是OrderID 示例结构包含以下字段:

      struct sampleStruct
      {
          string StockName;
          int Quantity;
          int StockType;
          enum_Status StockStatus;       // the declaration: enum enum_Status { Accepted, Cancel, Executed }
          double Price;
          DateTime TradeTime;
      }

现在假设我们有两条包含值的记录:

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

所以保存的字符串集合将是名称 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"

现在,过了一段时间我有一个上面那种保存的字符串集合,我知道它包含上面指定的结构,所以我运行这样的函数:

    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);

我希望有足够的数据来帮助我。 再次感谢。

0 个答案:

没有答案
相关问题