Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Defining a Dictionary<string, Dictionary<string, int>>

I am trying to define a static readonly dictionary of dictionary object in C# and am not sure if this is the correct way to store an object that consists of 1 key and 2 values. This code doesn’t work but it shows the logic of what I am trying to achieve.

private static readonly Dictionary<string, Dictionary<string, int>> StudentMapping = new Dictionary<string, Dictionary<string, int>>
        {
            {"Liam", new Dictionary<string, int>{"broadway", 1}},
            {"Emily", new Dictionary<string, int>{"math", 1}}
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

am not sure if this is the correct way to store an object that consists of 1 key and 2 values

To store 2 int values for each String key, use a ValueTuple of (int, int) for TValue:

C# has special-case syntax for using ValueTuple:

private static readonly Dictionary<string,(int broadway, int math)> StudentMapping = new Dictionary<string,(int broadway, int math)>
{
    { "Liam" , ( broadway: 1, math: 1 ) },
    { "Emily", ( broadway: 1, math: 1 ) },
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading