2013-05-15 85 views
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;        
} 

回答

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]++; 
} 
+0

什麼是itemCol1,這個語句爲itemCol1 [CurrCatId] ++; – NoviceToDotNet

+0

@NoviceToDotNet,而'itemColl [CurrCatId] ++'爲你提供這個'如果鍵存在,那麼我想增加1的值。 –

+0

我想增加一個密鑰的價值,如果在會話中存在.. – NoviceToDotNet

1

編輯:對不起,我以前不明白的問題。您只需嘗試使用該密鑰,這樣的:

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

使用try-catch因此,如果由於某種原因,關鍵是不存在的,你可以處理錯誤。

+4

像這是矯枉過正。 Dictionary提供了很好的方法,比如'ContainsKey'和'TryGetValue',這取決於你需要什麼。更好地堅持他們 - 更容易閱讀,可能更好的表現。 – Pako

+1

Pako是對的。邁克爾的回答比我的好。 – Renan

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