John Baum
John Baum

Reputation: 3331

Best way to add key-value pairs to a dictionary in C#

I am using a dictionary in C# to store some key-value pairs and had a question on the best way to populate the dictionary.

I need to do some other operations in order to find and add my key-value pairs to my dictionary. After those operations I may have found a key-value to add to the dictionary or I could have found nothing.

My question is how I should populate the dictionary?

Upvotes: 13

Views: 55718

Answers (2)

Timmerz
Timmerz

Reputation: 6199

your pseudo code is right.

public void Process( bool add, Dictionary<string, string> dictionary )
{
   if( add ) dictionary.Add( "added", "value" );
}

you could also use an extension method:

static class Program
{
    public static void AddIfNotNull(this Dictionary<string,object> target, string key, object value )
    {
        if( value != null )
            target.Add( key, value );
    }

    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>( );

        dictionary.AddIfNotNull( "not-added",    null );
        dictionary.AddIfNotNull( "added",       "true" );

        foreach( var item in dictionary )
            Console.WriteLine( item.Key );

        Console.Read( );
    }

}

Upvotes: 3

Shadow Wizard
Shadow Wizard

Reputation: 66389

Not sure what you ask here, but here is how I handle dictionary to either add or update a value based on a key:

string key = "some key here";
string value = "your value";
if (myDict.ContainsKey(key))
{
    myDict[key] = value;
}
else
{
    myDict.Add(key, value);
}

You can wrap this in a method if you like:

void AddOrUpdate(Dictionary<string, string> dict, string key, string value)
{
    if (dict.ContainsKey(key))
    {
        dict[key] = value;
    }
    else
    {
        dict.Add(key, value);
    }
}

//usage:
AddOrUpdate(myDict, "some key here", "your value");

You can also use the TryGetValue method but can't see any obvious advantage in this.

Upvotes: 23

Related Questions