Dictionary<string, int> illegParking = new Dictionary<string, int>();ide
鍵:inData.LOTIDspa
值:inData.ISILLEGPARKINGcode
1、判斷鍵存不存在。blog
dictionary中是不容許有重複項的,這樣才能按key索引到惟一一個value。索引
if (illegParking.ContainsKey(inData.LOTID)) { illegParking[inData.LOTID] = inData.ISILLEGPARKING; } else { illegParking.Add(inData.LOTID, inData.ISILLEGPARKING); }
2、幾種遍歷方式:string
Dictionary<string, int> list = new Dictionary<string, int>(); foreach (var item in list) { Console.WriteLine(item.Key + item.Value); } //經過鍵的集合取 foreach (string key in list.Keys) { Console.WriteLine(key + list[key]); } //直接取值 foreach (int val in list.Values) { Console.WriteLine(val); } //非要採用for的方法也可 Dictionary<string, int> list = new Dictionary<string, int>(); List<string> test = new List<string>(list.Keys); for (int i = 0; i < list.Count; i++) { Console.WriteLine(test[i] + list[test[i]]); }
3、涉及到移除某個鍵值的時候it
不能在foreach循環裏面移除,由於會致使錯誤:集合已修改;可能沒法執行枚舉操做。能夠改用for循環io
//dicmodels是個dictionaryfor循環
List<string> keys = new List<string>(dicModels.Keys); for (int i = keys.Count - 1; i >= 0; i--) { }