Reputation: 9876
I'm collecting data dynamically and I've chosen Dictionary<int, string>
as data structure to store this data.
At the beginning of my method I declare a variable :
Dictionary<int, string> templatesKeyName = new Dictionary<int, string>();
at the end of the method I want templatesKeyName
to contains all pairs of int (ids) and Names relevent for this request. So for example I have:
private static Dictionary<int, string> GetTemplateForUserWithAccount()
{
Dictionary<int, string> kv = new Dictionary<int, string>();
//populate the `kv` dictionary
return kv;
}
and I want to be able to do something like:
if(Client.Accounts.Count > 0)
{
templatesKeyName.Add(GetTemplateForUserWithAccount());
}
Obviously .Add()
extension expects two arguments but I wasn't able to find out how can I pass the values from the method without writing first assigning the result to e temporary Dictionary and then iterating with foreach
.Also, most likely I will get single result most of the time so iteration is not something that I consider really.
Upvotes: 0
Views: 964
Reputation: 101701
You can create an extension method for that:
public static void AddRange<T,K>(this Dictionary<T,K> source, IEnumerable<KeyValuePair<T,K>> values)
{
foreach(var kvp in values)
{
if(!source.ContainsKey(kvp.Key))
source.Add(kvp.Key, kvp.Value);
}
}
And use it like the following:
templatesKeyName.AddRange(GetTemplateForUserWithAccount());
Upvotes: 1