HashTable集合(键值对集合)
foreach循环
注:在键值对集合中用foreach循环来查看其中的元素
class Program
{
static void Main(string[] args)
{
//创建键值对对象
Hashtable ht = new Hashtable();
//先添加键(Keys)再添加值(Value)
ht.Add(1, "Rose");
ht.Add(9, "敲可爱");
ht.Add(3, true);
ht.Add(false, "假的");
ht[5]="也可赋值";//也可用于添加数据
ht[1]="把Rose替换了";//把已存在的键对应的值替换
//移除集合中所有元素
ht.Clear();
//遍历ht的键
foreach (var item in ht.Keys)
{
Console.WriteLine("键是{0};值是{1}",item,ht[item]);
}
}
}
注:var推断类型
使用var时,需要在声明var变量的同时必须给它赋值。
for循环和foreach循环
class Program
{
static void Main(string[] args)
{
//定义数组
int[] vs = new int[] { 1, 2, 2, 3, 4, 4, 55, 2 };
//for循环
for (int i = 0; i < vs.Length; i++)
{
Console.WriteLine(vs[i]);//vs[i]表示数组中的每个元素
}
Console.WriteLine("==================================>");
//foreach循环
foreach (var item in vs)//item表示数组中的每个元素
{
Console.WriteLine(item);
}
}
}
注
(1)键值对集合中,键必须是唯一的,值可以重复
(2) 先添加键(Keys)再添加值(Value)
(3)通过键来找值