在 C# 中检查 Hashtable 是否包含特定键
csharpserver side programmingprogramming
要检查 Hashtable 是否包含特定键,代码如下 −
示例
using System; using System.Collections; public class Demo { public static void Main(){ Hashtable hash = new Hashtable(); hash.Add("One", "Katie"); hash.Add("Two", "John"); hash.Add("Three", "Barry"); hash.Add("Four", ""); hash.Add("Five","Harry"); hash.Add("Six", "F"); hash.Add("Seven", "Tom"); hash.Add("Eight","Andy"); hash.Add("Nine", "I"); hash.Add("Ten", "Tim"); Console.WriteLine("Hashtable Key and Value pairs..."); foreach(DictionaryEntry entry in hash){ Console.WriteLine("{0} and {1} ", entry.Key, entry.Value); } Console.WriteLine("Is the Hashtable having fixed size? = "+hash.IsFixedSize); Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly); Hashtable hash2 = Hashtable.Synchronized(hash); Console.WriteLine("Is Hash synchronized = "+hash2.IsSynchronized); Console.WriteLine("Does Hashtable contains the key Ten = "+hash.Contains("Ten")); } }
输出
这将产生以下输出 −
Hashtable Key and Value pairs... One and Katie Ten and Tim Five and Harry Three and Barry Seven and Tom Two and John Four and Eight and Andy Nine and I Six and F Is the Hashtable having fixed size? = False If Hashtable read-only? = False Is Hash synchronized = True Does Hashtable contains the key Ten = True
示例
现在让我们看另一个例子 −
using System; using System.Collections; public class Demo { public static void Main(){ Hashtable hash = new Hashtable(); hash.Add("1", "AB"); hash.Add("2", "BC"); hash.Add("3", "DE"); hash.Add("4", "EF"); hash.Add("5", "GH"); hash.Add("6", "IJ"); hash.Add("7", "KL"); hash.Add("8", "MN"); hash.Add("9", "OP"); hash.Add("10", "QR"); Console.WriteLine("Value at key 3 = "+hash["3"]); Console.WriteLine("Does Hashtable contains the key 12 = "+hash.Contains("12")); } }
输出
这将产生以下输出 −
Value at key 3 = DE Does Hashtable contains the key 12 = False