36

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";
?>
gotqn
  • 42,737
  • 46
  • 157
  • 243
arbme
  • 4,831
  • 11
  • 44
  • 57

6 Answers6

66

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];
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • Are you sure that access by index is part of the definition of associative array? See http://en.wikipedia.org/wiki/Associative_array – Odrade Jul 12 '10 at 18:58
  • @Odrade: I am not at all ;) That's why I edited my answer to specifically refer to "PHP's associative array" (probably right after your comment). – Dan Tao Jul 12 '10 at 18:59
  • @Odrade: in case of PHP arrays, they aren't really accessible "by index" - rather, integers can be keys alongside strings (and there is a very convoluted conversion scheme in place, such that `8` and `"8"` are the same key but `"08"` is not). They aren't indices in a sense that they do not identify the position of the element in the array. – Pavel Minaev Jul 12 '10 at 19:08
  • Im now getting an error Thrown: "Index was outside the bounds of the array.". Any ideas?? var headers = new Dictionary();
    string[] headersSplit = line.Split(':');
    string hname = headersSplit[0];
    string hvalue = headersSplit[1]; <-- ERROR
    headers[hname] = hvalue;
    Console.WriteLine("Header Added: {0} {1}", hname, hvalue);
    – arbme Jul 12 '10 at 19:21
  • @arbme: The text you are splitting must not contain a ':' character. See the update at the bottom of my answer. – Dan Tao Jul 12 '10 at 19:26
  • Thanks Dan Tao it was a DOH moment! Forgot HTTP headers end with \r\n :) Thanks agian! – arbme Jul 12 '10 at 19:31
  • @Pavel: Thanks for pointing that out. My knowledge of PHP is shaky at best! – Dan Tao Jul 12 '10 at 19:34
  • If you set headers through PHP there is not need for the \r\n as it does it automatically. Its just when dealing with raw headers you must use the correct format. Header1\r\nHeader2\r\nHeader3\r\n\r\nContent – arbme Jul 12 '10 at 19:46
  • @Pavel I was responding to an old version of the answer. I can't see it in the revision history, but that's probably because he edited it pretty quickly after the original post. – Odrade Jul 12 '10 at 21:06
6

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"];
Mau
  • 14,234
  • 2
  • 31
  • 52
5

You could use a Dictionary<TKey, TValue>:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary["key_name"] = "value1";
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

Try a dictionary:

var dictionary = new Dictionary<string, string>();
dictionary.Add("key_name", "value1");
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
1

You can also use a KeyedCollection http://msdn.microsoft.com/en-us/library/ms132438%28v=vs.110%29.aspx where your value is a complex type and has a unique property.

You have your collection inherit from KeyedCollection, example ...

    public class BlendStates : KeyedCollection<string, BlendState>
    {
    ...

This requires you to override the GetKeyForItem method.

    protected override string GetKeyForItem(BlendState item)
    {
        return item.DebugName;
    }

Then, in this example, the collection is indexed by string (the debug name of the BlendState):

    OutputMerger.BlendState = BlendStates["Transparent"];
Gavin Williams
  • 446
  • 1
  • 4
  • 14
1

Since everyone else said dictionary, I decided I would answer with 2 arrays. One array would be an index into the other.

You didn't really specify the data type that you would find at a particular index so I went ahead and chose string for my example.

You also didn't specify if you wanted to be able to resize this later. If you do, you would use List<T> instead of T [] where T is the type and then just expose some public methods for add for each list if desired.

Here is how you could do it. This could also be modified to pass in the possible indexes to the constructor or make it however you would do it.

class StringIndexable
{
//you could also have a constructor pass this in if you want.
       public readonly string[] possibleIndexes = { "index1", "index2","index3" };
    private string[] rowValues;
    public StringIndexable()
    {
        rowValues = new string[ColumnTitles.Length];
    }

    /// <summary>
    /// Will Throw an IndexOutofRange Exception if you mispell one of the above column titles
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    public string this [string index]
    {
        get { return getOurItem(index); }
        set { setOurItem(index, value); }


    }

    private string getOurItem(string index)
    {
        return rowValues[possibleIndexes.ToList().IndexOf(index.ToLower())];

    }
    private void setOurItem(string index, string value)
    {
        rowValues[possibleIndexes.ToList().IndexOf(index.ToLower())] = value;
    }

}

You would then call it like so :

  StringIndexable YourVar = new YourVar();
  YourVar["index1"] = "stuff";
  string myvar = YourVar["index1"];
Alexander Ryan Baggett
  • 2,347
  • 4
  • 34
  • 61