C# Dictionary使用
Dictionary
类型:System.Collections.Generic.Dictionary
eg:Dictionary<string, int> illegParking = new Dictionary<string, int>();
键:inData.LOTID
值:inData.ISILLEGPARKING
在C#中,如果您尝试在Dictionary中不经过键的存在性检查直接使用键来访问值,可能会导致以下问题:
1.引发异常:如果您尝试使用一个未存在的键来访问值,将会触发KeyNotFoundException异常,这可能导致程序崩溃。
2.产生空引用:如果您在尝试访问值之前没有检查键的存在性,当所需的键不存在时,将会得到null(对于引用类型值)或者默认值(对于值类型值),这可能导致意外行为或者错误的计算结果。
为了避免以上问题,您应该在尝试访问Dictionary中的值之前,始终先检查键是否存在,可以使用ContainsKey方法或TryGetValue方法来进行检查。例如:
```csharp Dictionary<string,int> myDictionary = new Dictionary<string,int>(); // 检查键是否存在后再进行访问 if (myDictionary.ContainsKey("someKey")) { int value = myDictionary["someKey"]; // 使用 value 进行其他操作 } else { // 处理键不存在的情况 } // 或者使用 TryGetValue 方法进行安全的访问 if (myDictionary.TryGetValue("someKey",out int value)) { // 使用 value 进行其他操作 } else { // 处理键不存在的情况 } ```
通过在访问Dictionary中的值之前进行键的存在性检查,可以确保程序在面对不存在的键时不会出现异常或意外行为,从而使程序更加稳定和可靠
1、判断键存不存在。
dictionary中是不允许有重复项的,这样才能按key索引到唯一一个value
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
if (illegParking.ContainsKey(inData.LOTID)) { illegParking[inData.LOTID] = inData.ISILLEGPARKING; } else { illegParking.Add(inData.LOTID, inData.ISILLEGPARKING); }
2、几种遍历方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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、涉及到移除某个键值的时候
不能在foreach循环里面移除,因为会导致错误:集合已修改;可能无法执行枚举操作。可以改用for循环
//dicmodels是个dictionary
List<string> keys = new List<string>(dicModels.Keys); for (int i = keys.Count - 1; i >= 0; i--) { }
4、Dictionary通过value获取对应的key值
用linq的几种方式
var keys = dic.Where(q => q.Value == "2").Select(q => q.Key); //get all keys List<string> keyList = (from q in dic where q.Value == "2" select q.Key).ToList<string>(); //get all keys var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first key
KeyValuePair 和 Dictionary 的关系和区别
结构:System.Collections.Generic.KeyValuePair<TKey, TValue>
1、KeyValuePair
a、KeyValuePair 是一个结构体(struct);
b、KeyValuePair 只包含一个Key、Value的键值对。
2、Dictionary
a、Dictionary 可以简单的看作是KeyValuePair 的集合;
b、Dictionary 可以包含多个Key、Value的键值对。
自定义类作为Dictionary的key