循环遍历字典集合以搜索键并增加值

Nov*_*Net 2 c# asp.net

我有一个字典,我放在会话中,在每个按钮点击我需要执行一些操作.

itemColl = new Dictionary<int, int>();
Run Code Online (Sandbox Code Playgroud)

我想搜索一个我在会话变量中维护的密钥,如果密钥存在,那么我想将相应密钥的值增加1,我该如何实现.

我正在尝试如下:

if (Session["CurrCatId"] != null)
{
    CurrCatId = (int)(Session["CurrCatId"]);
    // this is the first time, next time i will fetch from session
    // and want to search the currcatid and increase the value from
    // corresponding key by 1.
    itemColl = new Dictionary<int, int>();
    itemColl.Add(CurrCatId, 1);
    Session["itemColl"] = itemColl;                            
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*oud 8

你非常接近,你只需要管理一些案例:

if (Session["CurrCatId"] != null)
{
    CurrCatId = (int)(Session["CurrCatId"]);

    // if the dictionary isn't even in Session yet then add it
    if (Session["itemColl"] == null)
    {
        Session["itemColl"] = new Dictionary<int, int>();
    }

    // now we can safely pull it out every time
    itemColl = (Dictionary<int, int>)Session["itemColl"];

    // if the CurrCatId doesn't have a key yet, let's add it
    // but with an initial value of zero
    if (!itemColl.ContainsKey(CurrCatId))
    {
        itemColl.Add(CurrCatId, 0);
    }

    // now we can safely increment it
    itemColl[CurrCatId]++;
}
Run Code Online (Sandbox Code Playgroud)