Search code examples
c#dictionarynestedmultikey

How to create and populate a nested dictionary with three keys


I have a unique double corresponding to a variation of three strings. I want to populate a dictionary or something such that I can call something like dict[key1][key2][key3] and get the value.

I've tried a whole bunch of things like

    Dictionary<string, Dictionary<string, double>> dict = new Dictionary<string, Dictionary<string, double>> {
        { "Foo", {"Bar", 1.2 } },
        { "Foo", {"Test", 3.4 } }
    };

Which gives me syntax errors and errors like "Error 4 A namespace cannot directly contain members such as fields or methods"

And

    Dictionary<double, Tuple<string, string>> dict = {
          {1.23, "Blah", "Foo"}
    };

Which gives me errors like "Error 1 Can only use array initializer expressions to assign to array types. Try using a new expression instead."

And

    object dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();

    dict["k1"] = new Dictionary<string, Dictionary<string, string>>();
    dict["k1"]["k2"] = new Dictionary<string, string>();
    dict["k1"]["k2"]["k3"] = 3.5;

Which gives me syntax errors and errors like "Error 2 Invalid token '"k1"' in class, struct, or interface member declaration"

How should I go about this? Thanks in advance.

![enter image description here][1]

enter image description here

Edit: Trying Jonesy's code:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        string[] grades = { "Grade 1", "Grade 5", "Grade 8", "ASTM A325", "316 Stainless", "Monel", "Brighton Best 1960" };
        string[] sizes = { "#1", "2", "3", "4", "5", "6", "8", "10", "12", "1/4", "5/16", "3/8", "7/16", "1/2", "9/16", "5/8", "3/4", "7/8", "1", "1-1/8", "1-1/4", "1-3/8", "1-1/2" };

        var dict = new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();
        dict["k1"] = new Dictionary<string, Dictionary<string, double>>();
        dict["k1"]["k2"] = new Dictionary<string, double>();
        dict["k1"]["k2"]["k3"] = 3.5;


        public Form1()
        {
            InitializeComponent();
        } 

Solution

  • your last attempt is close, you want:

    var dict = new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();
    dict["k1"] = new Dictionary<string, Dictionary<string, double>>();
    dict["k1"]["k2"] = new Dictionary<string, double>();
    dict["k1"]["k2"]["k3"] = 3.5;
    

    you want var instead of object

    (or Dictionary<string, Dictionary<string, Dictionary<string, double>>> if you like scrolling)

    and your very last string should be a double.