Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set array key as string not int?

Tags:

c#

.net

I am trying to set the array keys as a strings like in the example below, but inC#.

<?php
$array = array();
$array['key_name'] = "value1";
?>
like image 881
arbme Avatar asked Jul 12 '10 18:07

arbme


3 Answers

The closest you get in C# is Dictionary<TKey, TValue>:

var dict = new Dictionary<string, string>();
dict["key_name"] = "value1";

Note that a Dictionary<TKey, TValue> is not the same as PHP's associative array, because it is only accessible by one type of key (TKey -- which is string in the above example), as opposed to a combination of string/integer keys (thanks to Pavel for clarifying this point).

That said, I've never heard a .NET developer complain about that.


In response to your comment:

// The number of elements in headersSplit will be the number of ':' characters
// in line + 1.
string[] headersSplit = line.Split(':');

string hname = headersSplit[0];

// If you are getting an IndexOutOfRangeException here, it is because your
// headersSplit array has only one element. This tells me that line does not
// contain a ':' character.
string hvalue = headersSplit[1];
like image 178
Dan Tao Avatar answered Nov 15 '22 23:11

Dan Tao


Uhm I'm guessing you want a dictionary:

using System.Collections.Generic;

// ...

var dict = new Dictionary<string, string>();
dict["key_name1"] = "value1";
dict["key_name2"] = "value2";
string aValue = dict["key_name1"];
like image 30
Mau Avatar answered Nov 15 '22 23:11

Mau


You could use a Dictionary<TKey, TValue>:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary["key_name"] = "value1";
like image 5
Darin Dimitrov Avatar answered Nov 15 '22 23:11

Darin Dimitrov