访问值
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 49 课,共 66 课。
在 C# 中,我们使用 Dictionary<TKey, TValue> 作为 HashMap 的对应类型。向 Dictionary 添加项后,你需要检索它们。
创建一个键为 string、值为 int 的字典:
Dictionary<string, int> studentScores = new Dictionary<string, int>();添加一些条目:
studentScores.Add("John", 95);
studentScores.Add("Mary", 88);使用键访问值:
int johnScore = studentScores["John"];运行上面的代码后,johnScore 中的值是:
95请小心!如果你尝试访问不存在的键,就会得到 KeyNotFoundException:
// 如果字典中没有 "Bob",这里会抛出异常
int bobScore = studentScores["Bob"];挑战
简单创建一个名为 GetValueByKey 的方法,它接受两个参数:
- 一个 Dictionary<string, int>(字典)。
- 要查找的字符串(键)。
该方法应尝试访问给定键对应的值,并且:
- 如果键存在,则输出该值。
- 如果键不存在,则输出 "Key not found"。
亲手试试
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
{
// 在这里编写代码
}
static void Main(string[] args)
{
// 读取 JSON 格式的字典:{"key1":value1,"key2":value2}
string dictionaryInput = Console.ReadLine();
string key = Console.ReadLine();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// 解析输入字符串,创建字典
if (!string.IsNullOrEmpty(dictionaryInput))
{
try
{
// 检查输入是否为 JSON 格式
if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
{
// 去掉花括号
string jsonContent = dictionaryInput.Substring(1, dictionaryInput.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);
dictionary.Add(keyMatch, valueMatch);
}
}
}
// Handle the original format "key1:value1,key2:value2" as fallback
else
{
string[] pairs = dictionaryInput.Split(',');
foreach (string pair in pairs)
{
string[] keyValue = pair.Split(':');
if (keyValue.Length == 2)
{
dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
}
}
}
GetValueByKey(dictionary, key);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器