Измените элемент словаря перед его удалением

#c#

#c#

Вопрос:

Мне нужно удалить элемент коллекции словарей, но прежде чем я удалю его, я должен изменить атрибут его объекта.

 class ColeccionAlquileres
{
    //creation of the collection        
    Dictionary<int, Alquiler> alquileres = new Dictionary<int, Alquiler>();

    //method implementation
    public int BajaAlquiler(int _identificador)
    {
        if (alquileres.Remove(_identificador))
        {
            Console.WriteLine("Articulo dado de baja");
            //here, the code that allow change the atribute of my object.
        }
        else throw new AlquilerInexistenteException();
    }
}
 

Комментарии:

1. Когда вы говорите «измените атрибут моего (/ его) объекта» , вы имеете в виду изменение свойства Alguiler объекта, который вы удаляете из словаря? Подумайте о чем-то подобном TryGetValue , прежде чем выполнять удаление. Если это удастся, предмет будет у вас в руке.

Ответ №1:

Вы проверяете существование элемента и получаете его одновременно с TryGetValue :

 if (alquileres.TryGetValue(_identificador, out var element))
{
    Console.WriteLine("Articulo dado de baja");
    element.Deleted = true; // (example) Set your property here.
    alquileres.Remove(_identificador);
}
 

Ответ №2:

Рассмотрим что-то вроде:

 public int BajaAlquiler(int _identificador)
{
    if (alquileres.TryGetValue(_identificador, out var alquiler))
    {
        alquiler.Name = "Removed";
        alquileres.Remove(_identificador);
        Console.WriteLine("removed");
        return _identificador;
    }
    //otherwise
    Console.WriteLine("not found");
    throw new AlquilerInexistenteException();
}
 

Или, что еще лучше, используйте шаблон «TryDoSomething» для вашего вызова:

 public bool TryRemoveAlquiler(int _identificador, out Alquiler objectRemoved)
{
    if (alquileres.TryGetValue(_identificador, out var alquiler))
    {
        alquiler.Name = "Removed";
        objectRemoved = alquiler;
        alquileres.Remove(_identificador);
        Console.WriteLine("removed");
        return true;
    }
    //otherwise
    Console.WriteLine("not found");
    objectRemoved = null;
    return false;
}
 

Таким образом, вы передаете удаленный объект обратно вызывающему (и он может изменить свойства). И, в качестве бонуса, вы удаляете исключение (для того, что на самом деле не является исключительным условием)