c# - Loop through a dictionary collection to search a key and increase value -
i have dictionary put in session , on each button click need perform operation.
itemcoll = new dictionary<int, int>(); i want search key maintain in session variable, if key exist want increase value 1 corresponding key, how can achive this.
i trying follows:
if (session["currcatid"] != null) { currcatid = (int)(session["currcatid"]); // first time, next time fetch session // , want search currcatid , increase value // corresponding key 1. itemcoll = new dictionary<int, int>(); itemcoll.add(currcatid, 1); session["itemcoll"] = itemcoll; }
you're pretty close, need manage few more cases:
if (session["currcatid"] != null) { currcatid = (int)(session["currcatid"]); // if dictionary isn't in session yet add if (session["itemcoll"] == null) { session["itemcoll"] = new dictionary<int, int>(); } // can safely pull out every time itemcoll = (dictionary<int, int>)session["itemcoll"]; // if currcatid doesn't have key yet, let's add // initial value of 0 if (!itemcoll.containskey(currcatid)) { itemcoll.add(currcatid, 0); } // can safely increment itemcoll[currcatid]++; }
Comments
Post a Comment