Code: Select all
public void Test()
{
ConcurrentDictionary dictionary = new();
dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");
foreach (var item in dictionary)
{
string foundItem;
if (dictionary.TryGetValue(item.Key, out foundItem))
{
if (foundItem == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
}
Code: Select all
public void Test2()
{
ConcurrentDictionary dictionary = new();
dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");
foreach (var item in dictionary)
{
string foundItem;
if (item.Value == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
Meine Verwirrung besteht darin, dass ich jedes Mal, wenn ich ein Element entfernen möchte, versuche, es zuerst abzurufen. dann entfernen Sie es. Aber zunächst habe ich die foreach-Schleife verwendet, was bedeutet, dass ich das Element bereits erhalten habe. Jede Idee wäre willkommen.