Dictionary<TKey,TValue>
は、アイテムを追加する2つの異なる方法があります。
void Add(TKey key, TValue value)
:Add
を呼び出しているため、あなたが言っているセマンティックは「これは存在しない、存在する」ということです。したがって、古いものか新しいものかを知ることができないため、重複挿入で例外が発生します。
インデクサー(TValue this[TKey key]
)は、「私がインデクサーゲッターを呼び出した場合、これを答えにしたい」という意味を持つ割り当てをサポートしています。
dict.Add(1, 1);
var x = dict[1]; // x == 1
dict.Add(1, 2); // throws
dict.Add(1, 1);
var x = dict[1]; // x == 1;
dict[1] = 2;
var y = dict[1]; // x == 1, y == 2.
var dict = new Dictionary<long, int>();
dict[1] = 35;
var x = dict[1]; // x == 35;
ContainsKey
は、ほとんど常に間違ったことです。値を安全に読み取っている場合は、TryGetValue
に電話してください。辞書を使用して何かが行われたかどうかを保存する場合は、HashSet<T>
を使用してください。 (Add
メソッドがbool
(true
を追加した場合はそれが存在しませんでした)、false
が追加されなかった場合(値は既に存在しました)))を返します。
具体的には、リストに追加する場合は、TryGetValueアプローチが最適です。または、ConcurrentDictionary使用:
TryGetValue:
List<string> list;
// Read the dictionary exactly once
if (!dict.TryGetValue(key, out list))
{
list = new List<string>();
// Write at most once.
dict[key] = list;
}
list.Add(value);
ConcurrentDictionary:
ConcurrentDictionary<long, List<string>> dict = new ConcurrentDictionary<long, List<string>>();
...
List<string> list = dict.GetOrAdd(key,() => new List<string>());
list.Add(value);
を私は、拡張メソッドは、ここで最良の選択だと思います。
も参照
http://stackoverflow.com/questions/11027369/how-to-correctly-handle-adding-new-item-to-dictionary – Piotshe
より一般的な拡張サンプルはこちらhttp://stackoverflow.com/questions/3850930 /多価辞書/ 41305901#41305901 – Slai