How to add an element to the dictionary <string, Dictionary <string, object >>?

I want users of my LayoutManager class to be able to write this:

LayoutManager layoutManager = new LayoutManager();
layoutManager.AddMainContentView("customers", "intro", 
    new View { Title = "Customers Intro", Content = "This is customers intro." });

But what syntax do I need to populate this dictionary in the dictionary in AddMainContentView () below?

public class LayoutManager
{
    private Dictionary<string, Dictionary<string, object>> _mainContentViews = new Dictionary<string, Dictionary<string, object>>();
    public Dictionary<string, Dictionary<string, object>> MainContentViews
    {
        get { return _mainContentViews; }
        set { _mainContentViews = value; }
    }

    public void AddMainContentView(string moduleKey, string viewKey, object view)
    {
        //_mainContentViews.Add(moduleKey, new Dictionary<string, object>(viewKey, view));
        //_mainContentViews.Add(moduleKey, viewKey, view);
        _mainContentViews.Add(moduleKey, ???);
    }

    ...
}
+3
source share
4 answers
public void AddMainContentView(string moduleKey, string viewKey, object view)
{
    Dictionary<string, object> viewDict = null;
    if (!MainContentViews.TryGetValue(moduleKey, out viewDict)) {
        viewDict = new Dictionary<string, object>();
        MainContentViews.Add(moduleKey, viewDict);
    }
    if (viewDict.ContainsKey(viewKey)) {
        viewDict[viewKey] = view;
    } else {
        viewDict.Add(viewKey, view);
    }
}
+4
source

??? can be filled in:

new Dictionary<string, object> { {viewKey, view} }
+1
source

:

public void AddMainContentView(string moduleKey, string viewKey, object view)
{
    if ( !_mainContentViews.ContainsKey(moduleKey))
    {
       Dictionary<string, object> newModule = new Dictionary<string, object>();
       newModule.Add(viewKey, view);

       _mainContentViews.Add(moduleKey, newModule);
    }
}
+1

Tuple (.. , ), , , Key, .

If possible, use a tuple key rather than nested dictionaries - the only problem then uniquely identifies all members of the module, which, if you are dealing with reasonable small collections of no more than a few thousand items, you can safely be brute force.

0
source

Source: https://habr.com/ru/post/1713357/


All Articles