本文實(shí)例講述了ASP.NET中Dictionary基本用法。分享給大家供大家參考,具體如下:
//Dictionary位于System.Collections.Generic命名空間之下/* * 使用Dictionary之前必須引用System.Collections.Generic命名空間; * 使用Dictionary時(shí)必須聲明其鍵和值的數(shù)據(jù)類(lèi)型(可以為任意類(lèi)型); *///聲明實(shí)例化Dictionary為dicSystem.Collections.Generic.Dictionary<int, string> dic = new System.Collections.Generic.Dictionary<int, string>();//為dic添加鍵和值dic.Add(100, "quber100");dic.Add(200, "quber200");//檢查是否存在300這個(gè)鍵if (!dic.ContainsKey(300)){ //新增加300(鍵)和對(duì)應(yīng)的quber300(值) dic.Add(300, "quber300");}//移除dic鍵為300的項(xiàng)dic.Remove(300);//獲取dic鍵值對(duì)總數(shù)int dicCount = dic.Count;Response.Write("循環(huán)獲取dic中的鍵和值:<br/>");//循環(huán)獲取dic中的鍵和值foreach (KeyValuePair<int, string> keyDic in dic){ Response.Write("key:" + keyDic.Key + ",value:" + keyDic.Value + "<br/>");}Response.Write("<hr/><br/>");Response.Write("循環(huán)獲取dic中的鍵:<br/>");//循環(huán)獲取dic中的鍵Dictionary<int, string>.KeyCollection keyDics = dic.Keys;foreach (int iKey in keyDics){ Response.Write("key:" + iKey + "<br/>");}Response.Write("<hr/><br/>");Response.Write("另一種方法循環(huán)獲取dic中的鍵:<br/>");//循環(huán)獲取dic中的鍵foreach (int iKey in dic.Keys){ Response.Write("key:" + iKey + "<br/>");}Response.Write("<hr/><br/>");Response.Write("循環(huán)獲取dic中的值:<br/>");//循環(huán)獲取dic中的值Dictionary<int, string>.ValueCollection valueDics = dic.Values;foreach (string strValue in valueDics){ Response.Write("value:" + strValue + "<br/>");}Response.Write("<hr/><br/>");Response.Write("另一種方法循環(huán)獲取dic中的值:<br/>");//循環(huán)獲取dic中的值foreach (string strValue in dic.Values){ Response.Write("value:" + strValue + "<br/>");}Response.Write("<hr/><br/>");Response.Write("獲取dic中單個(gè)鍵和值:<br/>");Response.Write("key:100,value:" + dic[100] + "<br/>");Response.Write("<hr/><br/>");Response.Write("檢查dic中是否存在鍵(100),并返回其值dicStr:<br/>");//檢查dic中是否存在鍵(100),并返回其值dicStrstring dicStr = string.Empty;if (dic.TryGetValue(100, out dicStr)){ Response.Write("OK");}else{ Response.Write("NO");}Response.Write("<hr/><br/>");
希望本文所述對(duì)大家asp.net程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選