Best Practice - Removing item from generic collection in C#

Posted by Matt Davis on Stack Overflow See other posts from Stack Overflow or by Matt Davis
Published on 2009-03-13T21:30:06Z Indexed on 2010/03/28 10:23 UTC
Read the original article Hit count: 338

I'm using C# in Visual Studio 2008 with .NET 3.5.

I have a generic dictionary that maps types of events to a generic list of subscribers. A subscriber can be subscribed to more than one event.

private static Dictionary<EventType, List<ISubscriber>> _subscriptions;

To remove a subscriber from the subscription list, I can use either of these two options.

Option 1:

ISubscriber subscriber;  // defined elsewhere
foreach (EventType event in _subscriptions.Keys) {
    if (_subscriptions[event].Contains(subscriber)) {
        _subscriptions[event].Remove(subscriber);
    }
}

Option 2:

ISubscriber subscriber;  // defined elsewhere
foreach (EventType event in _subscriptions.Keys) {
    _subscriptions[event].Remove(subscriber);
}

I have two questions.

First, notice that Option 1 checks for existence before removing the item, while Option 2 uses a brute force removal since Remove() does not throw an exception. Of these two, which is the preferred, "best-practice" way to do this?

Second, is there another, "cleaner," more elegant way to do this, perhaps with a lambda expression or using a LINQ extension? I'm still getting acclimated to these two features.

Thanks.

EDIT

Just to clarify, I realize that the choice between Options 1 and 2 is a choice of speed (Option 2) versus maintainability (Option 1). In this particular case, I'm not necessarily trying to optimize the code, although that is certainly a worthy consideration. What I'm trying to understand is if there is a generally well-established practice for doing this. If not, which option would you use in your own code?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .net-3.5