What is the best way to add multiple values to a Dictionary if I don't want to call ".Add()
" multiple times.
Edit: I want to fill it after initiation! there are already some values in the Dictionary!
So instead of
myDictionary.Add("a", "b"); myDictionary.Add("f", "v"); myDictionary.Add("s", "d"); myDictionary.Add("r", "m"); ...
I want to do something like this
myDictionary.Add(["a","b"], ["f","v"],["s","d"]);
Is there a way to do so?
Note: If you have multiple values acting as the key, you would define a class to encapsulate those values and provide proper overrides of GetHashCode and Equals so that the dictionary could recognize their equality.
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
In this dictionary, keys are strings, and with each key string, we have a list of numbers associated as a value field. So, basically, in this dictionary, multiple values are associated with a key.
I think the dictionary only has one key value.
You can use curly braces for that, though this only works for initialization:
var myDictionary = new Dictionary<string, string> { {"a", "b"}, {"f", "v"}, {"s", "d"}, {"r", "m"} };
This is called "collection initialization" and works for any ICollection<T>
(see link for dictionaries or this link for any other collection type). In fact, it works for any object type that implements IEnumerable
and contains an Add
method:
class Foo : IEnumerable { public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { } // ... } Foo foo = new Foo { {1, 2, 3}, {2, 3, 4} };
Basically this is just syntactic sugar for calling the Add
-method repeatedly. After initialization there are a few ways to do this, one of them being calling the Add
-methods manually:
var myDictionary = new Dictionary<string, string> { {"a", "b"}, {"f", "v"} }; var anotherDictionary = new Dictionary<string, string> { {"s", "d"}, {"r", "m"} }; // Merge anotherDictionary into myDictionary, which may throw // (as usually) on duplicate keys foreach (var keyValuePair in anotherDictionary) { myDictionary.Add(keyValuePair.Key, keyValuePair.Value); }
Or as extension method:
static class DictionaryExtensions { public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); foreach (var keyValuePair in source) { target.Add(keyValuePair.Key, keyValuePair.Value); } } } var myDictionary = new Dictionary<string, string> { {"a", "b"}, {"f", "v"} }; myDictionary.Add(new Dictionary<string, string> { {"s", "d"}, {"r", "m"} });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With