Set array key as string not int?

前端 未结 6 1021
耶瑟儿~
耶瑟儿~ 2020-12-03 06:58

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



        
相关标签:
6条回答
  • 2020-12-03 07:05

    Try a dictionary:

    var dictionary = new Dictionary<string, string>();
    dictionary.Add("key_name", "value1");
    
    0 讨论(0)
  • 2020-12-03 07:12

    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"];
    
    0 讨论(0)
  • 2020-12-03 07:19

    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"];
    
    0 讨论(0)
  • 2020-12-03 07:26

    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];
    
    0 讨论(0)
  • 2020-12-03 07:30

    You could use a Dictionary<TKey, TValue>:

    Dictionary<string, string> dictionary = new Dictionary<string, string>();
    dictionary["key_name"] = "value1";
    
    0 讨论(0)
  • 2020-12-03 07:30

    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"];
    
    0 讨论(0)
提交回复
热议问题