Initialising a KeyValuePair Array
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.
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.
No, you can't do this - because an array always has a fixed size. If you don't specify that size to start with, what size would you expect to be used? You either have to specify the size itself or the contents (which allows the size to be inferred). For example:
int[] x = new int[10]; // Explicit size
int[] y = new int[] { 1, 2, 3, 4, 5 }; // Implicit size
int[] z = { 1, 2, 3, 4, 5 }; // Implicit size and type
List<T>
is definitely your friend for collections where you don't know the size to start with.
Why not rather use
List<KeyValuePair<string, string>>
Have a look at List Class
How about this?
var kvpArr = new List<KeyValuePair<string,string>>();
精彩评论