开发者

Help me convert this 2d array code from PHP to C#

Please help me re-write this code sample in PHP to C#:

$stringArray = array();
$stringArray['field1'] = 'value1';
$stringArray['field2'] = 'value2';
$stringArray['field3'] = 'value3';

forea开发者_StackOverflow社区ch ($stringArray as $key => $value)
{
    echo $key . ': ' . $value;
    echo "\r\n";
}


Named arrays do not exist in C#. An alternative is to use a Dictionary<string, string> to recreate a similar structure.

Dictionary<string, string> stringArray = new Dictionary<string, string>();
stringArray.Add("field1", "value1");
stringArray.Add("field2", "value2");
stringArray.Add("field3", "value3");

In order to iterate through them, you can use the following:

foreach( KeyValuePair<string, string> kvp in stringArray ) {
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}


var map = new Dictionary<String, String>
              {
                  { "field1", "value1" },
                  { "field2", "value2" },
                  { "field3", "value3" }
              }

Or without the collection initializer.

var map = new Dictionary<String, String>();

map["field1"] = "value1";
map["field2"] = "value2";
map["field3"] = "value3";

There is even a specialized class StringDictionary to map string to strings in the often overlooked namespace System.Collections.Specialized, but I prefer Dictionary<TKey, TValue> because it implements a richer set of interfaces.


You are trying to recreate an associative array - in C# I would usually use a Dictionary

Dictionary<string,string> stringArray = new Dictionary<string,string>();

and then you can assign values in two ways

stringArray["field1"] = "value1";
stringArray.Add("field2","value2");

Dictionaries can be used to store any key/value pair combination, such as:

Dictionary<int,string>()
Dictionary<long,KeyValuePair<string,long>>()
etc.

If you absolutely know that you only need a key that is a string that will be returning a value that is a string then you can also use a NameValueCollection

NameValueCollection stringArray = new NameValueCollection();

and again you can use the same two methods to add values

stringArray["field1"] = "value1";
stringArray.Add("field2","value2");

Both datatypes also have other convenience methods like

stringArray.Clear(); // make it empty
stringArray.Remove("field1"); // remove field1 but leave everything else

check out your intellisense in visual studio for more good stuff

Additional nodes

Note that a NameValueColelction does not (solely) provide a one-to-one mapping - you can associate multiple values with a single name.

var map = new NameValueCollection();

map.Add("Bar", "Foo");
map.Add("Bar", "Buz");

// Prints 'Foo,Buz' - the comma-separated list of all values
// associated with the name 'Bar'.
Console.WriteLine(map["Bar"]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜