Set array key as string not int?

前端 未结 6 1058
耶瑟儿~
耶瑟儿~ 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: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 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];
        }
    
        /// 
        /// Will Throw an IndexOutofRange Exception if you mispell one of the above column titles
        /// 
        /// 
        /// 
        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"];
    

提交回复
热议问题