Home > Backend Development > C#.Net Tutorial > Using hash tables and dictionaries in C#

Using hash tables and dictionaries in C#

WBOY
Release: 2023-08-30 13:49:02
forward
842 people have browsed it

在 C# 中使用哈希表和字典

Hashtable

Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.

Some of the commonly used methods in Hashtable class are −

Sr.No. Method & Description
1 public virtual void Add(object key, object value);

Adds an element with the specified key and value into the Hashtable.

2 public virtual void Clear();

Removes all elements from the Hashtable.

3 public virtual bool ContainsKey(object key);

Determines whether the Hashtable contains a specific key.

4 public virtual bool ContainsValue(object value);

Determines whether the Hashtable contains a specific value.

The following is an example showing the usage of Hashtable class in C# −

Example

 Live Demo

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Hashtable ht = new Hashtable();

         ht.Add("D01", "Finance");
         ht.Add("D02", "HR");
         ht.Add("D03", "Operations");

         if (ht.ContainsValue("Marketing")) {
            Console.WriteLine("This department name is already in the list");
         } else {
            ht.Add("D04", "Marketing");
         }

         ICollection key = ht.Keys;

         foreach (string k in key) {
            Console.WriteLine(k + ": " + ht[k]);
         }
         Console.ReadKey();
      }
   }
}
Copy after login

输出

D04: Marketing
D02: HR
D03: Operations
D01: Finance
Copy after login

字典

字典是C#中的键值对集合。Dictionary包含在System.Collection.Generics命名空间中。

以下是一些方法:

序号方法及描述
1Add

在字典中添加键值对

2Clear()

移除所有的键和值

3Remove

移除指定键的元素

4ContainsKey

检查字典中是否存在指定的键

5ContainsValue

检查字典中是否存在指定的键值

6Count

计算键值对的数量

7Clear

从字典中移除所有元素

让我们看看如何向字典中添加元素并显示数量:

示例

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {

      IDictionary <int, int> d = new Dictionary <int, int> ();
      d.Add(1,44);
      d.Add(2,34);
      d.Add(3,66);
      d.Add(4,47);
      d.Add(5,76);

      Console.WriteLine(d.Count);
   }
}
Copy after login

The above is the detailed content of Using hash tables and dictionaries in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template