您的位置:首页 > 编程语言 > C#

C#学习笔记之Hashtable集合

2016-05-10 15:43 627 查看
1、Hashtable:键值对集合

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 实例化Hashtable对象。
Hashtable ht = new Hashtable();
ht.Add(1, "张三");
ht.Add(2, true);
ht.Add(3, '男');
ht.Add(false, "错误的"); // 集合中可以添加任意类型的元素

// 遍历集合中的元素
for (int i = 0; i < ht.Count; i++)
{
// 该方法只能输出:"张三", true, '男'。因为 ht[i]中i是键,那么
// 输出的就是通过键获取到的值。
Console.WriteLine(ht[i]);
}

Console.WriteLine("*************");

// 使用for循环不能遍历键值对中的数据,可以使用foreach循环
foreach (var item in ht.Keys) // 遍历键
{
Console.WriteLine(ht[item]); // 根据键输出值,可以输出集合中所有的值
}

Console.ReadKey();
}
}
}</span>
ht[6] = "新的值";
// 添加键值对

ht[1] = "把张三替换掉";
// 该键值对重新赋值

ht.ContainKey("abc");  // 判断是否包含某个键,如果包含返回true,否则返回false。

ht.Clear();  // 清空键值对集合

ht.Remove(3);
 // 根据键移除某个键值对
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: