c#中的hashtable集合是根据键的哈希码组织的键值对的集合。哈希码是使用哈希码函数计算的。
哈希表中的每个元素都是具有唯一键的键值对。键也必须是非空的。值可以为空和重复。
在本文中,我们将讨论如何检查哈希表集合是否为空。
如何检查哈希表集合是否为空?c#中实现哈希表集合的类是hashtable类。我们可以通过计算哈希表中存在的元素数量来检查哈希表集合是否为空。
为此,我们可以使用 hashtable 类的“count”属性,该属性返回哈希表中的元素数量。
因此,如果 count 属性返回 0,则表示哈希表为空,如果返回大于 0 的值,则表示哈希表有元素。
我们首先了解一下hashtable类的count属性的原型。
语法public virtual int count { get; }
返回值 - int32 类型的属性值
描述 - 获取哈希表中包含的键值对的数量。
命名空间system.collections
从上面对 count 属性的描述可以看出,我们可以使用该属性获取哈希表集合中键值对的数量。
现在让我们看一些编程示例,它们将帮助我们理解这个 count 属性。
示例让我们看看第一个程序如何检查哈希表是否为空。程序如下。
using system;using system.collections;class program { public static void main() { // create a hashtable hashtable mytable = new hashtable(); //get the count of items in hashtable int mysize = mytable.count; if(mysize == 0) console.writeline(hashtable is empty); else console.writeline(the hashtable is not empty. it has {0} item(s), mysize); } }
在这个程序中,我们创建了一个 hashtable 对象,但没有向其中添加任何元素。然后我们使用 count 属性检索哈希表中存在的元素的计数。最后,计算 count 属性返回的值,并相应地显示消息,指示哈希表是否为空。
输出程序生成以下输出。
hashtable is empty
由于哈希表中没有元素,因此显示消息:哈希表为空。
现在让我们向上面程序中的哈希表添加一些元素。现在我们使用“add()”方法将两个元素添加到哈希表中。
示例程序如下所示。
using system;using system.collections;class program { public static void main() { // create a hashtable hashtable mytable = new hashtable(); mytable.add(1, one); mytable.add(2, two); //get the count of items in hashtable int mysize = mytable.count; if(mysize == 0) console.writeline(hashtable is empty); else console.writeline(the hashtable is not empty. it has {0} item(s)., mysize); }}
输出这里我们向哈希表添加了两个元素。现在输出更改为如下所示。
the hashtable is not empty. it has 2 item(s)
正如我们所见,count 属性返回哈希表中的元素数量。
现在让我们看另一个例子以更好地理解。
示例程序如下。
using system;using system.collections;class program { public static void main() { // create a hashtable hashtable langcode = new hashtable(); langcode.add(perl, ); //get the count of items in hashtable int hashtabsize = langcode.count; if(hashtabsize == 0) console.writeline(hashtable is empty); else console.writeline(hashtable is not empty. it has {0} item(s), hashtabsize); }}
输出这里我们有一个 langcode 哈希表,其中有一个元素。我们再次使用 count 属性来返回哈希表中的元素数量。该程序的输出如下所示。
hashtable is not empty. it has 1 item(s)
由于哈希表中有一个元素,因此会适当地给出消息。现在让我们删除哈希表中存在的元素。为此,我们只需注释掉向哈希表添加元素的行即可。
示例程序如下。
using system;using system.collections;class program { public static void main() { // create a hashtable hashtable langcode = new hashtable(); //langcode.add(perl, ); //get the count of items in hashtable int hashtabsize = langcode.count; if(hashtabsize == 0) console.writeline(hashtable is empty); else console.writeline(hashtable is not empty. it has {0} item(s), hashtabsize); }}
输出现在哈希表中没有任何元素。因此,当我们在此哈希表上使用 count 属性时,它返回零。因此输出显示哈希表为空。
hashtable is empty
因此,由于 hashtable 类中没有直接方法来检查哈希表是否为空,因此我们使用 hashtable 类的 count 属性来获取哈希表中元素的数量。如果 count 返回 0,则我们得出哈希表为空的结论。如果它返回一个非零值,则意味着哈希表中有元素。
以上就是检查 hashtable 集合是否为空的 c# 程序的详细内容。