C#Dictionary<TKey、TValue>类使用哈希表的概念。它根据键存储值。它只包含唯一键。在键的帮助下,无涯教程可以轻松地搜索或删除元素。它位于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) { Dictionarynames = new Dictionary (); names.Add("1","Sonoo"); names.Add("2","Peter"); names.Add("3","James"); names.Add("4","Ratan"); names.Add("5","Irfan"); foreach (KeyValuePair kv in names) { Console.WriteLine(kv.Key+" "+kv.Value); } } }
输出:
1 Sonoo 2 Peter 3 James 4 Ratan 5 Irfan
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)