美文网首页
集合 - HashTable

集合 - HashTable

作者: 帅帅的浪浪zl | 来源:发表于2016-12-14 22:24 被阅读0次

using System;
using System.Collections; // 集合
using System.Collections.Generic; // 泛型集合

namespace 集合之HashTable
{
class Person {
public string user_Name;
public int user_Id;
}

class MainClass
{
    public static void Main (string[] args)
    {
        // 为什么要引入集合概念:

        // 演示数组的局限性

        // 1.数组的局限性
        // 数组只能存储相同类型的数据,比如int[] 数组只能存储int数据

        // 2.数组存在大量垃圾数据

// string[] strs = new string[2];
// strs[0] = "张三";
// strs[1] = "张三";
// foreach (string item in strs) {
// Console.WriteLine (item);
// }

        // 3.数组不能动态的扩展长度


        // 集合
        // Hashtable;
        // ArrayList;
        // Stack;
        // Queue;

        // 泛型集合
        // ArrayList --> List<T>
        // ArrayList al = new ArrayList();
        // List<int> li = new List<int>();
        // Hashtable --> Dictionary<Type,Type>

        // HashTable
        // Key -> value
        // Key2 -> value
        // 这里的key是唯一的

// Hashtable ht = new Hashtable();
// ht.Add (001,"老王");
// ht.Add (002,"老王2");
// ht.Add (003,"老王3");

// // 通过key取value
// Console.WriteLine (ht[001]);
//
// // 通过一个key移除一个value值
// ht.Remove(001);
//
// // 全部移除
// ht.Clear();

        // 查找Key || value

// if (ht.Contains(001)) {
// Console.WriteLine ("True");
// }
//
// if (ht.ContainsKey(001)) {
// Console.WriteLine ("True");
// }
// if (ht.ContainsValue("老王")) {
// Console.WriteLine ("True");
// }
// // 遍历所有的key
// foreach (var item in ht.Keys) {
// Console.WriteLine (item);
// }
//
// // 遍历所有的value
// foreach (var item in ht.Values) {
// Console.WriteLine (item);
// }

        // 遍历所有key - value
        Hashtable ht = new Hashtable();

        Person p1 = new Person();
        p1.user_Name = "老王";
        p1.user_Id = 1001;

        Person p2 = new Person();
        p2.user_Name = "老张";
        p2.user_Id = 1002;

        ht.
        ht.Add (p1.user_Id, p1);
        ht.Add (p2.user_Id, p2);

        // 获取字段枚举遍历器
        IDictionaryEnumerator ide = ht.GetEnumerator();
        while (ide.MoveNext()) {

// ide.Entry;
// 将取出的内容转换成字典实体
DictionaryEntry de = (DictionaryEntry)ide.Current;
// 通过字典实体内的字段value 取出当时你存value时候的对象P,取出来的对象
// 需要转换(和你当时存的value类型是一致的)
Person per = de.Value as Person;
Console.WriteLine ("用户的id:{0},用户的姓名:{1}",per.user_Id,per.user_Name);
}

    }
}

}

相关文章

网友评论

      本文标题:集合 - HashTable

      本文链接:https://www.haomeiwen.com/subject/tklymttx.html