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

Time:04-07

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}}
        }

CodePudding user response:

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 ) },
}
  •  Tags:  
  • c#
  • Related