Код: Выделить всё
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
}
}
}
}
}
Код: Выделить всё
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
}
}
}
}
Меня смущает то, что всякий раз, когда я хочу удалить элемент, я сначала пытаюсь его получить, затем удалите его. Но во-первых, я использовал цикл foreach, то есть элемент уже получен. Любая идея будет оценена по достоинству.
Подробнее здесь: https://stackoverflow.com/questions/291 ... rrentdicti
Мобильная версия