Dictionary<string, int> illegParking = new Dictionary<string, int>();
- key: inData.LOTID
值: inData.ISILLEGPARKING
1 , it is determined key exists or not.
dictionary is not allowed to have duplicates, so as to press the key index to a unique value .
if (illegParking.ContainsKey (inData.LOTID)) { illegParking [inData.LOTID] = inData.ISILLEGPARKING; } Else { illegParking.Add (inData.LOTID, inData.ISILLEGPARKING); }
2 , traversing several ways:
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 comes to the removal of a key
Foreach loop which can not be removed, as it will lead to error: the collection has been modified; enumeration operation may not execute . You can use a for loop
// dicmodels a dictionary
List<string> keys = new List<string>(dicModels.Keys); for (int i = keys.Count - 1; i >= 0; i--) { }