C# Dictionary使用
作者:互联网
Dictionary<string, int> illegParking = new Dictionary<string, int>();
键:inData.LOTID
值:inData.ISILLEGPARKING
1、判断键存不存在。
dictionary中是不允许有重复项的,这样才能按key索引到唯一一个value。
if (illegParking.ContainsKey(inData.LOTID)) { illegParking[inData.LOTID] = inData.ISILLEGPARKING; } else { illegParking.Add(inData.LOTID, inData.ISILLEGPARKING); }View Code
2、几种遍历方式:
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]]); }View Code
3、涉及到移除某个键值的时候
不能在foreach循环里面移除,因为会导致错误:集合已修改;可能无法执行枚举操作。可以改用for循环
//dicmodels是个dictionary
List<string> keys = new List<string>(dicModels.Keys); for (int i = keys.Count - 1; i >= 0; i--) { }
标签:Console,Dictionary,C#,inData,list,WriteLine,使用,new 来源: https://www.cnblogs.com/peterYong/p/10881869.html