将数组键设置为字符串而不是int?

时间:2010-07-12 18:54:09

标签: c# .net

我正在尝试将数组键设置为字符串,如下例所示,但在C#中。

<?php
$array = array();
$array['key_name'] = "value1";
?>

6 个答案:

答案 0 :(得分:56)

你在C#中最接近的是Dictionary<TKey, TValue>

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

请注意,Dictionary<TKey, TValue> 与PHP的关联数组相同,因为可通过一种类型的键访问(TKey - 在上面的例子中是string,而不是字符串/整数键的组合(感谢Pavel澄清这一点)。

那就是说,我从来没有听说过.NET开发人员抱怨过这个问题。


回应你的评论:

// 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];

答案 1 :(得分:5)

嗯,我猜你想要一本字典:

using System.Collections.Generic;

// ...

var dict = new Dictionary<string, string>();
dict["key_name1"] = "value1";
dict["key_name2"] = "value2";
string aValue = dict["key_name1"];

答案 2 :(得分:4)

您可以使用Dictionary<TKey, TValue>

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

答案 3 :(得分:2)

尝试字典:

var dictionary = new Dictionary<string, string>();
dictionary.Add("key_name", "value1");

答案 4 :(得分:0)

您还可以使用KeyedCollection http://msdn.microsoft.com/en-us/library/ms132438%28v=vs.110%29.aspx,其中您的值是复杂类型且具有唯一属性。

您的集合继承自KeyedCollection,例如......

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

这要求您覆盖GetKeyForItem方法。

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

然后,在此示例中,集合按字符串索引(BlendState的调试名称):

    OutputMerger.BlendState = BlendStates["Transparent"];

答案 5 :(得分:0)

由于其他人都说字典,我决定用2个数组回答。 一个数组将成为另一个数组的索引。

您没有真正指定在特定索引中找到的数据类型,因此我继续为我的示例选择字符串。

您也没有指定是否希望以后能够调整大小。如果这样做,您将使用List<T>而不是T [],其中T是类型,然后根据需要公开一些公共方法以便为每个列表添加。

这是你如何做到的。这也可以修改为将可能的索引传递给构造函数或者然后执行它。

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;
    }

}

然后你会这样称呼它:

  StringIndexable YourVar = new YourVar();
  YourVar["index1"] = "stuff";
  string myvar = YourVar["index1"];