Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

collections

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 :)

like image 893
Ryan Rodemoyer Avatar asked Nov 24 '10 13:11

Ryan Rodemoyer


People also ask

What is native in C?

Native code is computer programming (code) that is compiled to run with a particular processor(such as an Intel *86-class processor) and its set of inctruction. If the same program is run on a computer with a different processor, software can be provided so that the computer emulates the original processor.

What is native C, C++?

The Native Development Kit (NDK) is a set of tools that allows you to use C and C++ code with Android, and provides platform libraries you can use to manage native activities and access physical device components, such as sensors and touch input.

Is C# a native code?

The C# compilation process has three states (C#, Intermediate Language, and native code) and two stages: going from C# to Common Intermediate Language and going from Intermediate Language to native code. NOTE Native code is sometimes referred to as machine code.

Is C++ a native language?

C++ is considered a native language because it compiles directly into machine code that can be understood by the underlying system. C# must first compile into Microsoft Intermediate Language (MSIL) before the just-in-time (JIT) compiler generates machine code. For this reason, C++ is typically faster than C#.


1 Answers

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.

like image 93
Jon Skeet Avatar answered Oct 28 '22 03:10

Jon Skeet