Help with Dictionary()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    #1

    Help with Dictionary()

    I need help getting this to work. I've got a dictionary object that I need to contain 57 items in. Each item is an int/string pair with the int being an identifier to the string. I'm putting the dictionary in a seperate class file so I don't bloat my main program with too many extra lines of code. I don't want to have any extra files for the user to download.

    Since I'm doing it in a class file, I'm trying to simply assign the values to the dictionary like this:

    Code:
    Dictionary<int, string> data = new Dictionary<int, string>()
    {
        myInt, myString
    };
    The problem is, I don't know how to assign the values into the dictionary using that method. I would rather stay away from making a method just to populate the dictionary if I can do it this way.

    Also, I'm not completely 100% decided on using a dictionary anyway. I basically want an associative array. In PHP this would be easy, since I can have an associative array, but C# makes it difficult.

    Can anyone please help me figure this out? If I do go with a dictionary, how would I provide an integer and return the string it's associated with?

    Finally, is a Dictionary or a Hashtable better for something like this?
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    There is no constructor that takes a series of data as parameters.
    You could make your own class that inherits from Dictionary maybe and have a constructor that does it?

    Comment

    • HaLo2FrEeEk
      Contributor
      • Feb 2007
      • 404

      #3
      Maybe I'm misunnderstandi ng the terminology here, but I'm not trying to pass them at parameters, I'm trying to do something similar to a list:

      List<int> myList = new List<int>() { 1, 2, 3};

      But with a dictionary.

      Regardless, I ended up writing a method to add them all, then another method to read the string back into my main program. It works and it's fast. I'd still like to find a more elegant solution though.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        That is an implicit constructor when you do that, its part of the Array class. I don't think that applies to a dictionary, but I could be wrong.

        Comment

        • ryuk
          New Member
          • Jun 2010
          • 1

          #5
          You can't do that.
          Instead of that way..
          Code:
          Dictionary<int, string> data = new Dictionary<int, string>()
          {
              { myInt, myString },
              { 1, string.Empty },
             { 2, null },
             { 3, "" }
          };

          Comment

          Working...