Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
jondavidjohn Avatar asked Jun 29 '11 19:06

jondavidjohn


People also ask

What is array of string in C?

In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.

Is array IEnumerable C#?

All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.


1 Answers

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" }
};
like image 117
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet