如何将项添加到Dictionary <string,dictionary <string,=“”object =“”>&gt;?</string,>

时间:2009-07-23 15:44:28

标签: c# collections dictionary

我希望我的LayoutManager类的用户能够写这个:

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

但是我需要在下面的AddMainContentView()字典中填写这个字典的语法是什么?

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, ???);
    }

    ...
}

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

???可以填写:

new Dictionary<string, object> { {viewKey, view} }

答案 2 :(得分:1)

这会有效吗?

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

答案 3 :(得分:0)

使用元组作为键(即没有嵌套字典,但只是合并键)并再次添加变得简单,或者您需要检查是否存在moduleKey,如果不是,则首先创建一个新的空字典。

如果可能的话,使用元组键而不是嵌套字典 - 然后唯一的问题就是唯一地识别模块的所有成员,如果你处理的合理的小集合只有几千个元素,那么你可以安全地蛮力。