1、 它使用键来访问集合中的元素。
当您使用键访问元素时,则使用哈希表,而且您可以识别一个有用的键值。哈希表中的每一项都有一个键/值对。键用于访问集合中的项目
//哈希表
Hashtable hs = new Hashtable();
//添加key/value键值对
//键值对:
//键:关键,相当于整个数据表中的唯一标识符,要求必须不能重复
//值:当对于这个件而言记录的值
//对:成对出现
hs.Add("E", "e");
hs.Add("B", "b");
hs.Add("A", "a");
//Count:获取包含在哈希表中键值对的数目
int count = hs.Count;
Console.WriteLine(count);
//清空
hs.Clear();
//判断哈希表是否包含特定键,其返回值为true或false
if (hs.Contains("E"))
{
hs.Remove("E");
}
//遍历哈希表
foreach (DictionaryEntry a in hs)
{
Console.Write(a.Key);
Console.Write(a.Value);
}
//对哈希表进行排序
ArrayList list = new ArrayList(hs.Keys);
list.Sort();
foreach (string s in list)
{
Console.Write(hs[s]);
}
排序列表类、堆栈、队列
2、它代表了一个先进先出的对象集合。
当您需要对各项进行先进先出的访问时,则使用队列。当您在列表中添加一项,称为入队,当您从列表中移除一项时,称为出队
Queue<string> strList = new Queue<string>();
/向队列加入元素
// strList.Enqueue("元素1");
// strList.Enqueue("元素2");
// strList.Enqueue("元素3");
/遍历元素
// foreach (string item in strList)
// {
// Console.WriteLine(item);
// }
/队长长度
// Console.Write("队列长度---");
// Console.WriteLine(strList.Count);
//取出最先加进去的元素,并删除,充分体现队列的先进先出的特性
/如队列中无元素,则会引发异常
// string mes1 = strList.Dequeue();
// Console.WriteLine(mes1);
/取出最先入队的元素,但并不删除
string mes = strList.Peek();
Console.Write("取出但不移除队头的元素----");
Console.WriteLine(mes);
///遍历队列,仍为三个元素
Console.WriteLine("队列剩余元素为---");
foreach (string item in strList)
{
Console.WriteLine(item);
}
///直接获得队列中的某个元素,
///如果索引越界,会引发异常
Console.Write("获取队列中的第2个元素----");
string s = strList.ElementAt(2);
Console.WriteLine(s);
///直接获得队列中的某个元素,
///如果索引越界,则会返回null,但不引发异常
Console.Write("获取队列中的第5个元素-----");
Console.WriteLine(strList.ElementAtOrDefault(5));
Console.Write("获取队列中的第1个元素-----");
Console.WriteLine(strList.ElementAtOrDefault(1));
///取出最先入队的元素,但并不删除
string pop = strList.Dequeue();
Console.Write("取出队头的元素----");
Console.WriteLine(mes);
///遍历队列,为2个元素
Console.WriteLine("队列剩余元素为---");
foreach (string item in strList)
{
Console.WriteLine(item);
}
// Console.ReadLine();
资源字典
//字典集合
Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");
//ContainsKey:判断是否包含指定的键
bool bo = myDic.ContainsKey("aaa");
Console.WriteLine(bo);
string value = "";
myDic.TryGetValue("aaa", out value);
Console.WriteLine(value);
//下面用foreach 来遍历键值对
//泛型结构体用来存储健值对
//foreach (KeyValuePair<string, string> kvp in myDic)
//{
// Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
//}
foreach (KeyValuePair<string, string> KV in myDic)
{
Console.WriteLine("key={0},value={1}", KV.Key, KV.Value);
}
//获取键的集合方法1
Dictionary<string, string>.KeyCollection keys = myDic.Keys;
foreach (string k in keys)
{
Console.WriteLine(k);
}
//获取键的集合方法2
foreach (string k in myDic.Keys)
{
Console.WriteLine("key={0}", k);
}
//获取值得集合方法1
foreach (string s in myDic.Values)
{
Console.WriteLine("value={0}", s);
}
//获取值得集合方法2
Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string v in values)
{
Console.WriteLine(v);
}