2

我有一本字典,我把它放在会话中,在每个按钮上单击我都需要执行一些操作。

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

3 回答 3

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]++;
}
于 2013-05-15T12:43:16.770 回答
1

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

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

使用 atry-catch以便如果由于某种原因密钥不存在,您可以处理错误。

于 2013-05-15T12:41:44.000 回答
1
var itemColl = Session["itemColl"];
if (!itemColl.ContainsKey(CurrCatId))
    itemColl[CurrCatId] = 0;
itemColl[CurrCatId]++;
于 2013-05-15T12:44:53.873 回答