Define Array and Keys in a literal way - C#
Trying to consolidate this...
string[] array = new string[];
开发者_开发技巧array[0] = "Index 0";
array[3] = "Index 3";
array[4] = "index 4";
Into one line...
Example in PHP
$array = array( 0 => "Index 0", 3 => "Index 3", 4 => "Index 4" );
I know I can do this
string[] array = { "string1", "string2", "string3" }
But how would i get the proper indexes in there?
It sounds like you're really after a Dictionary<int, string>
rather than a traditional C# array:
var dictionary = new Dictionary<int, string>
{
{ 0, "Index 0" },
{ 3, "Index 3" },
{ 4, "Index 4" }
};
In C# you can't. If you wanted specific indexes you'd have to pass in null
values to hold the place of the empty object.
It sounds like you're really after a Dictionary<TKey, TValue>
instead.
As far I know, you can't skip index numbers in regular array (e.g. 0,1,2 and then 4 without 3). You need to use different data structure like Dictionary or Hashtable.
Hashtable ht = new Hashtable()
{
{"key1", "value1"},
{"key2", "value2"}
};
From my understanding you cannot define arrays in the way you want. Other posters have indicated you can use associative arrays (Dictionaries)
At best you can create a workaround:
string[] array = {"array0", "", "array2", "array3"};
or
string[] array = new string[4];
array[0] = "array0";
array[2] = "array2";
精彩评论