Define an array and keys in a literal key - C #

Trying to consolidate this ...

string[] array = new string[]; array[0] = "Index 0"; array[3] = "Index 3"; array[4] = "index 4"; 

In one line ...

PHP example

 $array = array( 0 => "Index 0", 3 => "Index 3", 4 => "Index 4" ); 

I know I can do it

 string[] array = { "string1", "string2", "string3" } 

But how can I get the indices I need?

+6
source share
4 answers

It looks like you really are after Dictionary<int, string> , and not a traditional C # array:

 var dictionary = new Dictionary<int, string> { { 0, "Index 0" }, { 3, "Index 3" }, { 4, "Index 4" } }; 
+9
source

In C # you cannot. If you need specific indexes, you need to pass null values ​​to hold the empty object.

It looks like you really are after Dictionary<TKey, TValue> .

+4
source

As far as I know, you cannot skip index numbers in a regular array (e.g. 0,1,2, then 4 without 3). You need to use another data structure such as Dictionary or Hashtable.

 Hashtable ht = new Hashtable() { {"key1", "value1"}, {"key2", "value2"} }; 
+2
source

From my understanding, you cannot define arrays the way you want. Other posters indicated that 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";

0
source

Source: https://habr.com/ru/post/891671/


All Articles