集合 - HashTable

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.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);
}


}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值