zoukankan      html  css  js  c++  java
  • Hashtable 数据遍历的几种方式

    Hashtable 在集合中称为键值对,它的每一个元素的类型是 DictionaryEntry,由于Hashtable对象的键和值都是Object类型,决定了它可以放任何类型的数据,

    下面我就把Hashtable对象中放置定义的一个类的几个对象。

    创建的类如下:

    //代码
    static void Main(string[] args)
    {
        Person person1 = new Person();
        person1.Age = 34;
        person1.Name = "Jacky";
        person1.Email = "Jacky@gmail.com";
        Person person2 = new Person();
        person2.Age = 23;
        person2.Name = "Ajay";
        person2.Email = "Ajay@gmail.com";
        Person person3 = new Person();
        person3.Age = 12;
        person3.Name = "Bill";
        person3.Email = "Bill@gmail.com";
        Person person4 = new Person();
        person4.Age = 23;
        person4.Name = "Gace";
        person4.Email = "Gace@gmail.com";
        Person person5 = new Person();
        person5.Age = 45;
        person5.Name = "Jim";
        person5.Email = "Jim@gmail.com";
        Hashtable ht = new Hashtable();
        ht.Add("1", person1);
        ht.Add("2", person2);
        ht.Add("3", person3);
        ht.Add("4", person4);
        ht.Add("5", person5);
        Console.WriteLine("请输入你的查询的用户名:");
        string strName = Console.ReadLine();
        //第一种方法
        foreach (string item in ht.Keys)
        {
            Person p = (Person)ht[item];
            if (strName == p.Name)
            {
                Console.WriteLine("查询后的结果是:" + p.Name + "	" + p.Email + "	" + p.Age);
            }
        }
    
        //第二种方法
        foreach (Person item in ht.Values)
        {
            if (item.Name == strName)
            {
                Console.WriteLine("查询后的结果是:" + item.Name + "	" + item.Email + "	" + item.Age);
            }
        }
    
        //第三种方法
        foreach (DictionaryEntry item in ht)
        {
            if (strName == ((Person)item.Value).Name)
            {
                Console.WriteLine("查询后的结果是:" + ((Person)item.Value).Name + "	" + ((Person)item.Value)."	" + ((Person)item.Value).Age);
            }
        }
        //第四种方法
        IDictionaryEnumerator id = ht.GetEnumerator();
        while (id.MoveNext())
        {
            Person p = (Person)ht[id.Key];
            if (p.Name == strName)
            {
                Console.WriteLine("查询后的结果是:" + p.Name + "	" + p.Email + "	" + p.Age);
            }
        }
    
    }
  • 相关阅读:
    超级简单:一步一步教你创建一小型的asp.net mvc 应用程序
    asp.net AJAX 验证用户名是否存在 Jquery
    生成缩略图、为图片添加文字水印、图片水印的类
    图Graph
    [转]Implementing a Generic Binary Tree in C#
    .net C#数据结构
    Why HTML5 is worth your time
    跳跃表SkipList
    C# LockFreeStack类
    [转]泛型弱引用
  • 原文地址:https://www.cnblogs.com/wolfocme110/p/4337015.html
Copyright © 2011-2022 走看看