Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a list of dictionaries as value of another dictionary?

I am trying to create a list of dictionaries as a value of another dictionary.

I basically want to store data like this

userPrivileges ["foo"]["a"] = 4;
userPrivileges ["foo"]["b"] = 8;
userPrivileges ["foo"]["c"] = 16;
userPrivileges ["bar"]["a"] = 4;

Here is what I tried

Dictionary<string, List<Dictionary<string, int>>> userPrivileges = new Dictionary<string, List<Dictionary<string, int>>>();

To add or update a key in the dictionary list I use the following method

protected void AddOrUpdateUserPrivilege(string moduleName, string key, int value)
{
    if (!this.userPrivileges.ContainsKey(moduleName))
    {
        var entry = new Dictionary<string, int>(key, value);

        this.userPrivileges.Add(moduleName, entry);
    } 
    else
    {
        this.userPrivileges[moduleName][key] |= value;
    }

}

Here is a screenshot of the syntax errors enter image description here

How can I add a new entry to the main directory? and how can I access/update the value of a dictionary in the list?

like image 656
Junior Avatar asked Dec 06 '25 21:12

Junior


1 Answers

Dictionaries don't have a constructor to insert elements. You can use the collection initializer syntax:

var entry = new Dictionary<string, int> 
{
    { key, value }
};

Your other issues don't line up with the fact that you have a Dictionary<string, List<Dictionary<string, int>>>, because you're using it as Dictionary<string, Dictionary<string, int>>.

Since your code appears to make sense as the latter, I would suggest changing your definition to be:

Dictionary<string, Dictionary<string, int>> userPrivileges = new Dictionary<string, Dictionary<string, int>>();
like image 197
Rob Avatar answered Dec 09 '25 14:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!