Reputation: 3331
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?
Should I use a function that returns a key-value pair if found and otherwise an empty one contained within a dictionary.Add(function()) call? I don't want to add an empty key-value pair to the dictionary, so I'm not sure how the return call for that function would work, or
Should I pass the dictionary to the function and add to it if needed? Like:
function(dictionary)
{
if (pair found)
{
dictionary.add(pair)
}
}
Upvotes: 13
Views: 55718
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
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