Ryan Rodemoyer
Ryan Rodemoyer

Reputation: 5692

Native C# .NET method to check if item exists in collection before adding

I find myself writing this quite frequently.

Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
if (!h.Contains(key))
{
    h.Add(key, value);
}

Is there a native method (perhaps something like AddIf() ??) that checks to see if it exists in the collection and if it does not, adds it to the collection? So then my example would change to:

Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
h.AddIf(key, value);

This would apply beyond a Hastable. Basically any collection that has a .Add method.

EDIT: Updated to add a value when adding to the Hashtable :)

Upvotes: 11

Views: 14134

Answers (5)

thecoop
thecoop

Reputation: 46098

There isn't such a method in the .NET framework. But you can easily write your own extension method:

public static void AddIfNotExists<T>(this ICollection<T> coll, T item) {
    if (!coll.Contains(item))
        coll.Add(item)
}

For IDictionary, I use this method (generally for Dictionary<TKey, List<TValue>> and variations):

public static TValue AddIfNotExists<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
    where TValue : new()
{
    TValue value;
    if (!dict.TryGetValue(key, out value))
    {
        value = new T();
        dict.Add(key, value);
    }
    return value;
}

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1500485

Well, you probably don't write that code, because Hashtable uses key/value pairs, not just keys.

If you're using .NET 3.5 or higher, I suggest you use HashSet<T>, and then you can just unconditionally call Add - the return value will indicate whether it was actually added or not.

EDIT: Okay, now we know you're talking about key/value pairs - there's nothing built-in for a conditional add (well, there is in ConcurrentDictionary IIRC, but...), but if you're happy to overwrite the existing value, you can just use the indexer:

h[key] = value;

Unlike Add, that won't throw an exception if there's already an entry for the key - it'll just overwrite it.

Upvotes: 19

Charles Bretana
Charles Bretana

Reputation: 146499

I often write a similar method in my custom Dictionary/Hashtable collections, as a Type FetchOrCreate(Key), not as an void AddIf(Key)

Upvotes: 0

Adam
Adam

Reputation: 629

For a hashtable you could write myHashtable[key] = myHashtable[key] ?? newValue where the right hand side would first check if myHashtable[key] evaluated to null and if not resolve to that otherwise resolve to newVale

Upvotes: 2

SLaks
SLaks

Reputation: 887413

Your code doesn't make sense, since a HashTable needs both a key and a value.

If you meant a HashSet<T>, calling Add will do nothing if the item is already there.

If you meant a Dictionary<TKey, TValue>, you can write dict[key] = value, which will add the key if it's not present or overwrite it if it is.

Upvotes: 1

Related Questions