C#字典操作

1. 创建一个字典

Dictionary<stirng,int> dictionary = new Dictionary<string,int>();

2. 在字典中添加元素

dictionary.Add("张三",56);

dictionary.Add("李四",21);

dictionary.Add("王五",9);

3. 通过key查找元素,并修改其值

string key= "张三";
if (dictionary.ContainsKey(key))
{
  dictionary[key] = dictionary[key] + 1;
}

4. 在文件中保存字典

在文件中保存字典,必须遍历元素后,将数据保存在字典中,而不是直接保存字典,例如:Write_File(path, Dictionary<string, int> dic)会出现序列化不成功。

方法:

通过KeyValuePair遍历元素

StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<string, int> dic in dictionary)
{
      stringBuilder.AppendLine("["+dic.Key+","+dic.Value+"]");
}
Write_File(path, stringBuilder.ToString());

仅遍历字典的keys属性

创建一个新的字典,该字典只保存key的字段   Dictionary<string, int>.KeyCollection

Dictionary<string, int>.KeyCollection dic = data.Keys;
foreach(var key in dic)
{
    label.Text = key;
}

 仅遍历字典的values属性

创建一个新的字典,该字典只保存value的字段 Dictionary<string, int>.ValueCollection

Dictionary<string, int>.ValueCollection dic_value = data.Values;
foreach(var value in dic_value)
{
    label_last.Text = value.ToString();
}

 5. 通过Remove方法移除指定的键值

if (dictionary.ContainsKey("张三"))
{
    data.Remove("张三");
}

移除所有的键和值

dictionary.Clear();

 6. 其它常见属性和方法的说明

  Comparer:           获取用于确定字典中的键是否相等的 IEqualityComparer。

  Count:                  获取包含在 Dictionary中的键/值对的数目。

  Item:                    获取或设置与指定的键相关联的值。

  Keys:                   获取包含 Dictionary中的键的集合。

  Values:                获取包含 Dictionary中的值的集合。

  Add:                    将指定的键和值添加到字典中。

  Clear:                  从 Dictionary中移除所有的键和值。

  ContainsKey:      确定 Dictionary是否包含指定的键。

  ContainsValue:   确定 Dictionary是否包含特定值。             

  GetEnumerator:  返回循环访问 Dictionary的枚举数。

  GetType:             获取当前实例的 Type。 (从 Object 继承。)

  Remove:             从 Dictionary中移除所指定的键的值。

  ToString:             返回表示当前 Object的 String。 (从 Object 继承。)

  TryGetValue:      获取与指定的键相关联的值。

posted @ 2022-09-26 13:08  浑浑噩噩一只小迷七  阅读(1344)  评论(0)    收藏  举报