tags:

views:

62

answers:

3

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

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

foreach ($stringArray as $key => $value)
{
    echo $key . ': ' . $value;
    echo "\r\n";
}
+1  A: 
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.

Daniel Brückner
Sorry my fault for not being more specific, wanted to add one at a time. Also added a loop thing at the end, upvoted anyways :)
Andrew G. Johnson
+4  A: 

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);
}
Andrew Moore
This also has the advantage of being strongly typed. Gotta love Generics.
Steve Wortham
@Steve: Best language feature implemented in CLR 2.0 **by far**.
Andrew Moore
Indeed. Most of the time these low level optimizations aren't really appreciated because it's often not where the bottleneck lies. But one of the few times I was able to observe the performance advantage was with some AI I wrote for a Tic Tac Toe game. Once I made the switch to Generics and eliminated the need for any type conversion whatsoever, I improved performance by over 25%.
Steve Wortham
There is also the StringDictionary class if you are only using strings in your values. I'm really not sure if it is better than a generic dictionary<string,string>, but it is a strongly typed hashtable, meant to work specifically with strings..
Francisco Noriega
just to complement my other post, you would use it like this: StringDictionary myCol = new StringDictionary(); myCol.Add( "red", "rojo" ); myCol.Add( "green", "verde" ); myCol.Add( "blue", "azul" );
Francisco Noriega
A: 

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"]);
mlennox
Thanks for the clarification Daniel - I don't use NameValueCollections that often (knowingly...) - cheers
mlennox