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

时间:2013-05-15 12:40:13

标签: c# asp.net

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

itemColl = new Dictionary<int, int>();

我想搜索我在会话变量中维护的密钥,如果密钥存在,那么我想将相应密钥的值增加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;                            
}

3 个答案:

答案 0 :(得分: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]++;
}

答案 1 :(得分:1)

编辑:抱歉,我之前没有理解这个问题。您只需尝试使用该密钥,如下所示:

try
{
    if (condition)
        itemColl[i]++;
}
catch
{
    // ..snip
}

使用try-catch,如果由于某种原因钥匙不在那里,您就可以处理错误。

答案 2 :(得分:1)

var itemColl = Session["itemColl"];
if (!itemColl.ContainsKey(CurrCatId))
    itemColl[CurrCatId] = 0;
itemColl[CurrCatId]++;