200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Hashtable几种常用的遍历方法

Hashtable几种常用的遍历方法

时间:2022-02-20 22:41:25

相关推荐

Hashtable几种常用的遍历方法

Hashtable

在System.Collection是命名空间李Hashtable是程序员经常用到的类,它以快速检索著称,是研发人员开发当中不可缺少的利器。

Hashtable表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。Hashtable的键必须是唯一的,没有有效的排序,他进行的是内在的排序。

Hashtable有以下4中遍历方式:

1、以string对象为键值遍历哈希表。

2、以自定义对象为键值遍历哈希表。

3、以DictionaryEntry对象为键值遍历哈希表。

4、通过继承IDictionaryEnumerator接口的对象来遍历哈希表。

using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp1{class Program{class Person{private int age;public int Age{get { return age; }set { age = value; }}private string name;public string Name{get { return name; }set { name = value; }}private string email;public string Email{get { return email; }set { email = value; }}}static void Main(string[] args){var a = new Person{Age = 34,Name = "Jacky",Email = "Jacky@"};var b = new Person{Age = 23,Name = "Ajay",Email = "Ajay@"};var c = new Person{Age = 12,Name = "Bill",Email = "Bill@"};var d = new Person{Age = 23,Name = "Gace",Email = "Gace@"};var e = new Person{Age = 45,Name = "Jim",Email = "Jim@"};var ht = new Hashtable{{ "1", a },{ "2", b },{ "3", c },{ "4", d },{ "5", e }};Console.WriteLine("请输入你的查询的用户名:");var strName = Console.ReadLine();//第一种方法foreach (string item in ht.Keys){var p = (Person)ht[item];if (strName == p.Name){Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);}}Console.WriteLine("华丽的分割线=========================================================");//第二种方法foreach (Person item in ht.Values){if (item.Name == strName){Console.WriteLine("查询后的结果是:" + item.Name + "\t" + item.Email + "\t" + item.Age);}}Console.WriteLine("华丽的分割线=========================================================");//第三种方法foreach (DictionaryEntry item in ht){if (strName == ((Person)item.Value).Name){Console.WriteLine("查询后的结果是:" + ((Person)item.Value).Name + "\t" + ((Person)item.Value).Email + "\t" + ((Person)item.Value).Age);}}Console.WriteLine("华丽的分割线=========================================================");//第四种方法IDictionaryEnumerator id = ht.GetEnumerator();while (id.MoveNext()){Person p = (Person)ht[id.Key];if (p.Name == strName){Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);}}Console.ReadKey();}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。