C#中的ContainsKey()方法
设置一个Hashtable集合,并向其中添加一些元素。
Hashtable h = new Hashtable(); h.Add(1, "Sam"); h.Add(2, "Jack"); h.Add(3, "Andy"); h.Add(4, "Katie"); h.Add(5, "Beth"); h.Add(6, "Benjamin");
使用该ContainsKey()方法检查哈希表中是否存在键。
让我们检查键3。它返回True,找到键。
h.ContainsKey(3));
示例
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable h = new Hashtable();
h.Add(1, "Sam");
h.Add(2, "Jack");
h.Add(3, "Andy");
h.Add(4, "Katie");
h.Add(5, "Beth");
h.Add(6, "Benjamin");
Console.WriteLine("键和值列表:");
foreach (var key in h.Keys ) {
Console.WriteLine("Key = {0}, Value = {1}",key , h[key]);
}
Console.WriteLine("Does the specified key exist? "+h.ContainsKey(3));
}
}输出结果
键和值列表: Key = 6, Value = Benjamin Key = 5, Value = Beth Key = 4, Value = Katie Key = 3, Value = Andy Key = 2, Value = Jack Key = 1, Value = Sam Does the specified key exist? True
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志