C#Dictionary字典


Dictionary是存儲鍵和值的集合
Dictionary是無序的,鍵Key是唯一的
Dictionary<Key,Value> dic = new Dictionary<Key,Value>();
Dictionary<string, int> dic = new Dictionary<string, int>();
//Add方法來添加鍵值對
dic.Add("YAOER",20);
dic.Add("FenLi", 18);
dic.Add("BaoBao", 20);
dic.Add("BaoBei", 18);
//獲取當前字典中KeyValue的個數
int count = dic.Count;
Console.WriteLine("當前字典里有"+count+"個KeyValue");
//檢查字典中是否包含指定的Key
bool b = dic.ContainsKey("YAOER");
//檢查字典中是否包含指定的Key
bool c = dic.ContainsValue(20);
//嘗試獲取指定的Key所對應的Value
int s;
bool bb = dic.TryGetValue("YAOER", out s);
//如果當前字典中包含YAOER這個Key,那么就獲取對應的Value並保存在s中,bb=true
//如果當前字典中不包含YAOER這個Key,那么 s = null,bb = false
//通過Key獲取Value
int age = dic["YAOER"];
Console.WriteLine(age);
//Remove方法來移除鍵值對
dic.Remove("YAOER");
//清空當前字典
dic.Clear();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM