C# Dictionary<TKey, TValue> 类使用哈希表的概念。它基于键存储值。它仅包含唯一键。借助 key,我们可以轻松地搜索或删除元素。它位于 System.Collections.Generic 命名空间中。
让我们看一个通用 Dictionary<TKey, TValue> 类的示例,该类使用 Add() 方法存储元素并使用 for-each 循环迭代元素。在这里,我们使用 KeyValuePair 类来获取键和值。
using System; using System.Collections.Generic; public class DictionaryExample { public static void Main(string[] args) { Dictionary<string, string> names = new Dictionary<string, string>(); names.Add("1","Sonoo"); names.Add("2","Peter"); names.Add("3","James"); names.Add("4","Ratan"); names.Add("5","Irfan"); foreach (KeyValuePair<string, string> kv in names) { Console.WriteLine(kv.Key+" "+kv.Value); } } }
输出:
1 Sonoo 2 Peter 3 James 4 Ratan 5 Irfan