This seems like a straightforward thing to do, but I don't seem to be able to work out the correct syntax. I currently have this:
KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string,string>[];
However, this seems to work:
KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string,string>[10];
But I don't know the size of the array initially. I know I can use a list of KVPs and I probably will, but I just wanted to know how / if this could actually be done.
To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
The default value is 100,000 key/value pairs.
KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. To expand on Chris' example (in which we have two dictionaries containing <string, int> pairs).
Arrays are fixed-size by definition. You can either specify the size as in your second code example, or you can have it inferred from the initialization:
KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>(...),
new KeyValuePair<string, string>(...),
...
}
If you want a variable length structure, I suggest you use the List<T>
.
For more information about arrays, see the C# programming guide.
How about this?
var kvpArr = new List<KeyValuePair<string,string>>();
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