0

文字列コレクション型を、さまざまな型のキーと値を含む辞書に変換しようとしています (ほとんどの場合、値は構造体になります。文字列コレクションの各文字列には、最初の要素と残りの要素にキーが含まれます。文字列には構造体要素(ディクショナリの値)が含まれます。もちろん、文字列には、構造体要素の型をデコードする必要がある構造体の各要素の正しい型が含まれます...私はそうしようとしましたが、私は行き止まりに遭遇し、可能性はありません...ググってみましたが、私のプログラムの多くのケースに一致すると思われるため、私のケースはかなり難しいです...これが私がやろうとしたことです

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

ここで、値を含む 2 つのレコードがあるとします。

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

それが私を助けるのに十分なデータであることを願っています。再度、感謝します。

4

0 に答える 0