HashMap 方法
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 52 课,共 66 课。
HashMap 方法提供了强大的方式来处理字典数据。让我们来了解一些常用方法:
检查字典中是否存在某个键:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);
bool hasApples = inventory.ContainsKey("apples");
// hasApples 的值将是 true获取字典中的所有键:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
// 获取所有键
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
Console.WriteLine(name);
}获取字典中的所有值:
// 获取所有值
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
Console.WriteLine(score);
}从字典中移除一项:
scores.Remove("Bob");
// 现在字典里只剩下 Alice 的分数。如果键存在并已被移除,Remove() 会返回 true;如果键不存在,则返回 false。移除不存在的键不会报错。
清除所有项:
scores.Clear();
// 字典现在是空的使用 .Count 获取字典中的项数:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
int total = scores.Count;
Console.WriteLine(total);
// 输出:2挑战
中等创建一个名为 ProcessDictionary 的方法,它接受一个 Dictionary<string, int> 作为参数,并执行以下操作:
- 打印
Keys:,然后打印所有键(每行一个) - 打印
Values:,然后打印所有值(每行一个) - 检查字典是否包含键
"total",并打印Contains 'total': True或Contains 'total': False - 如果键
"temp"存在,则将其删除 - 打印
Count:,然后打印执行这些操作后字典中的项目数量(使用字典的.Count属性)
亲手试试
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static void ProcessDictionary(Dictionary<string, int> dict)
{
// 在这里编写你的代码
}
// 忽略主程序代码,它会将字符串转换为 HashMap
static void Main(string[] args)
{
Dictionary<string, int> inputDict = new Dictionary<string, int>();
// 读取第一行,检查是否为 JSON 格式
string firstLine = Console.ReadLine();
// 检查输入是否为 JSON 格式
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// 处理 JSON 输入
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// 按引号外的逗号拆分
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// 使用正则表达式提取键和值
Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
if (match.Success)
{
string keyMatch = match.Groups[1].Value;
int valueMatch = int.Parse(match.Groups[2].Value);
inputDict.Add(keyMatch, valueMatch);
}
}
ProcessDictionary(inputDict);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
else
{
try
{
// Process traditional input format
int n = int.Parse(firstLine);
for (int i = 0; i < n; i++)
{
string[] pair = Console.ReadLine().Split(':');
string key = pair[0];
int value = int.Parse(pair[1]);
inputDict.Add(key, value);
}
ProcessDictionary(inputDict);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器