views:

231

answers:

4

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 fill this dictionary in a 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  A: 
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);
    }
}
AgileJon
Depending on semantics, you either want:"viewDict[viewKey] = view;"or"viewDict.Add(viewKey, view);"but you don't need both. Your semantics are now equivalent to the first option.
Eamon Nerbonne
Exactly what I need to build, works well, thanks.
Edward Tanguay
A: 

The ??? could be filled with:

new Dictionary<string, object> { {viewKey, view} }
Matt Kellogg
A: 

Would this work:

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);
    }
}
Mel Green
A: 

Either use a Tuple as the key (i.e. no nested Dictionaries, but simply a merged key) and adding once again becomes simple, or you'll need to check whether a moduleKey is present, and if not first create a new empty Dictionary.

If possible, use a tuple-key rather than nested dictionaries - the only issue then becomes uniquely identifying all members of a module, which, if you're dealing with reasonable small collections with no more than a few thousand elements, you can safely brute force.

Eamon Nerbonne