5

たとえば、次のような辞書を作成するとします。

Dictionary<string, MyClass> dic = new Dictionary<string, MyClass>();

dic.add("z1", val1);
dic.add("abc9", val2);
dic.add("abc8", val3);
dic.add("ABC1", val4);

だから私がするとき:

foreach (KeyValuePair<string, MyClass> kvp in dic)
{
}

これらの値が「z1」、「abc9」、「abc8」、「ABC1」として取得される保証はありますか?

そして、最初にこれを行うとしたら、「z1」、「abc8」、「ABC1」になりますか?

dic.Remove("abc9");
4

4 に答える 4

6

いいえ。MSDNから(強調鉱山)

KeyValuePair<TKey, TValue>列挙のために、ディクショナリ内の各項目は、値とそのキーを表す構造体として扱われます。アイテムが返される順序は定義されていません

繰り返しの順序をより細かく制御したい場合は、OrderedDictionaryクラスを参照してください。

于 2013-09-26T21:06:09.040 に答える
5

The short answer is No. Order is not guaranteed in a Dictionary<TKey, TValue>, nor should you count on order being maintained.

You might want to check into OrderedDictionary instead.

Example:

OrderedDictionary d = new OrderedDictionary();

d.Add("01", "First");
d.Add("02", "Second");
d.Add("03", "Third");
d.Add("04", "Fourth");
d.Add("05", "Fifth");

for(int i = 0; i < d.Count; i++) // Print values in order
{
   Console.WriteLine(d[i]);
}

Note there's no generic OrderedDictionary<TKey,TValue> version for some odd reason. However, this question has some hints on how to implement one.

于 2013-09-26T21:05:30.737 に答える
1

これらの値が「z1」、「abc9」、「abc8」、「ABC1」として取得される保証はありますか?

絶対違う。常にキーと値のペアの順序付けられDictionary<,>ていないコレクションとして扱います。実装の詳細として、値を追加するだけの場合、通常は挿入順に表示されますが、これに依存するべきではありません。

ドキュメントから:

KeyValuePair<TKey, TValue>列挙のために、ディクショナリ内の各項目は、値とそのキーを表す構造体として扱われます。アイテムが返される順序は定義されていません。

(私のものを強調してください。)

特定の順序が必要な場合は、別のコレクションを使用する必要があります。キーでフェッチできる必要がある場合は、辞書と組み合わせて使用​​する可能性があります。(たとえば、 anIList<TKey>と aを維持することはまったく珍しいことではありません。)Dictionary<TKey, TValue>

于 2013-09-26T21:05:22.600 に答える
0

No, there is no guarantee of elements order. Also, it can be different depending on actual implementation of IDictionary<...> interface.

于 2013-09-26T21:05:30.977 に答える