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

WBOY
发布: 2023-08-30 13:49:02
转载
830人浏览过

在 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();
      }
   }
}
登录后复制

输出

D04: Marketing
D02: HR
D03: Operations
D01: Finance
登录后复制

字典

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

以下是一些方法:

序号 方法及描述
1 Add

在字典中添加键值对

迦恩计算机资源网源码(图书销售类)
迦恩计算机资源网源码(图书销售类)

采用三层架构开发,前台集成了产品在线展示,用户注册、在线调查、在线投稿后台有类别管理\图书管理\订单管理\会员管理\配送范围管理\邮件列表\广告管理\友情链接管理等后台添加图书时自动生成缩略图和文字水印主要参考了petshop的设计架构、使用了Asp.net2.0中很多MemberShip、master等新功能后台管理地址/web/admin/ 超级管理员账号密码均为aspx1特别提示:该系统需要

迦恩计算机资源网源码(图书销售类) 0
查看详情 迦恩计算机资源网源码(图书销售类)

2 Clear()

移除所有的键和值

3 Remove

移除指定键的元素

4 ContainsKey

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

5 ContainsValue

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

6 Count

计算键值对的数量

7 Clear

从字典中移除所有元素

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

示例

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);
   }
}
登录后复制

以上就是在 C# 中使用哈希表和字典的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号