2

私は C# を使用しており、intervalRecordsPerObjecttypeという名前の辞書を持っていDictionary<string, List<TimeInterval>>ます。辞書を反復処理する必要があります。問題は、辞書を繰り返し処理するたびに、さらにKeyValuePairs追加される可能性があることです。ディクショナリが大きくなるにつれて、新しいエントリも繰り返し処理する必要があります。

まず、私はこれを行いました:私に格言foreachを与えた単純なループInvalidOperationException

Collection was modified; enumeration operation may not execute.

ToList()C# がbeforeforeachループで変換するときに変化し続ける場合、この方法で Dictionary を反復処理できないことはわかっています。

forキーを一時配列にコピーし、単純なループを使用して辞書を反復処理しCount、新しいエントリが辞書に追加されるたびに、対応するキーも配列に追加できることを知っています。さて、問題は単純な配列が動的に拡大できないことであり、必要なサイズがどれくらいになるかを事前に知りません。

先に進むために、私はこれを行うと思いました:

List<string> keyList = new List<string>(intervalRecordsPerObject.Count);
intervalRecordsPerObject.Keys.CopyTo(keyList.ToArray(), 0);

これもできない。keyListは現在空であるためkeyList.toArray()、長さ 0 の配列を返しますArgumentException

Destination array is not long enough to copy all the items in the collection. Check array index and length.

ハマった!さらに何を試すことができますか?助けてくれてありがとう。

追加 1:

ディクショナリには、特定のオブジェクトが存在する時間間隔が格納されます。キーはオブジェクトの ID です。反復ごとに新しいエントリが追加される場合 (最悪の場合) もあれば、一度も追加されない場合もあります。エントリが追加されるかどうかは、いくつかの条件 (オブジェクトが他の間隔と重なるかどうかなど) によって決定されます。これにより、ID と対応する間隔リストが変更され、辞書に新しいエントリとして追加されます。

4

2 に答える 2

1

このようなもの:

List<string> keys = dict.Keys.ToList();

for (int i = 0; i < keys.Count; i++)
{
    var key = keys[i];

    List<TimeInterval> value;

    if (!dict.TryGetValue(key, out value))
    {
        continue;
    }

    dict.Add("NewKey", yourValue);
    keys.Add("NewKey");
}

ここでの秘訣は、List<T>by indexを列挙することです! このように、新しい要素を追加しても、 はfor (...)それらを「キャッチ」します。

一時的な使用による他の可能な解決策Dictionary<,>

// The main dictionary
var dict = new Dictionary<string, List<TimeInterval>>();

// The temporary dictionary where new keys are added
var next = new Dictionary<string, List<TimeInterval>>();

// current will contain dict or the various instances of next
// (multiple new Dictionary<string, List<TimeInterval>>(); can 
// be created)
var current = dict;

while (true)
{
    foreach (var kv in current)
    {
        // if necessary
        List<TimeInterval> value = null;

        // We add items only to next, that will be processed
        // in the next while (true) cycle
        next.Add("NewKey", value);
    }

    if (next.Count == 0)
    {
        // Nothing was added in this cycle, we have finished
        break;
    }

    foreach (var kv in next)
    {
        dict.Add(kv.Key, kv.Value);
    }

    current = next;
    next = new Dictionary<string, List<TimeInterval>>();
}
于 2013-08-30T12:30:30.873 に答える
0

Keysコンテンツではなく位置ごとにアクセスし、法線を使用できますFor loop(制限なしで追加/削除を許可します)。

for (int i = 0; i < dict.Keys.Count; i++)
{
    string curKey = dict.Keys.ElementAt(i);
    TimeInterval curVal = dict.Values.ElementAt(i);
    //TimeInterval curVal = dict[curKey];

   //Can add or remove entries
}
于 2013-08-30T12:38:28.133 に答える