Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising a KeyValuePair Array

Tags:

arrays

c#

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.

like image 871
Paul Michaels Avatar asked Nov 18 '10 07:11

Paul Michaels


People also ask

How do you declare a key value pair?

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.

What is KeyValuePair C#?

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.

What is the default value of KeyValuePair?

The default value is 100,000 key/value pairs.

What is the difference between KeyValuePair and dictionary C#?

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).


2 Answers

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.

like image 187
Anders Fjeldstad Avatar answered Oct 03 '22 15:10

Anders Fjeldstad


How about this?

var kvpArr = new List<KeyValuePair<string,string>>();
like image 32
cdhowie Avatar answered Oct 03 '22 13:10

cdhowie