C#字典
示例
Dictionary<TKey,TValue>是一个映射。对于给定的键,字典中可以有一个值。
using System.Collections.Generic;
var people = new Dictionary<string, int>
{
{ "John", 30 }, {"Mary", 35}, {"Jack", 40}
};
//读取数据
Console.WriteLine(people["John"]); //30
Console.WriteLine(people["George"]); //抛出KeyNotFoundException
int age;
if (people.TryGetValue("Mary", out age))
{
Console.WriteLine(age); //35
}
//添加和更改数据
people["John"] = 40; //这样覆盖值是可以的
people.Add("John", 40); // Throws ArgumentException since "John" already exists
//遍历内容
foreach(KeyValuePair<string, int> person in people)
{
Console.WriteLine("Name={0}, Age={1}", person.Key, person.Value);
}
foreach(string name in people.Keys)
{
Console.WriteLine("Name={0}", name);
}
foreach(int age in people.Values)
{
Console.WriteLine("Age={0}", age);
}使用集合初始化时重复密钥
var people = new Dictionary<string, int>
{
{ "John", 30 }, {"Mary", 35}, {"Jack", 40}, {"Jack", 40}
}; // throws ArgumentException since "Jack" already exists
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法