C# 集合类(四)

C# 集合类自己经常用到: 数组(Array)、动态数组(ArrayList)、列表(List)、哈希表(Hashtable)、字典(Dictionary),对于经常使用的这些数据结构,做一个总结,便于以后备忘使用。

1 所在命名空间 

using System.Collections.Generic;

using System.Collections;

2 字典(Dictionary)

字典也是键值对的集合,更像是Hashtable类的泛型版本,通过泛型的方式支持不同类型的键值对。Dictionary<Tkey,TValue>

2.1 初始化

//创建不同副本,根据需要使用不同的构造函数,zd10-01

Dictionary<int, string> dict1 = new Dictionary<int, string>();
//
Dictionary<int, string> dict2 = new Dictionary<int, string>(10);

2.2 遍历方法

private void NavigateKeys(Dictionary<int,string>dt)
{
foreach (object key in dt.Keys)
{
MessageBox.Show(key.ToString() + "kkk");
}
}
private void NavigateValues(Dictionary<int,string>dt)
{
foreach (object value in dt.Values)
{
MessageBox.Show(value.ToString() + "vvv");
}
}
private void NavigateEntrys(Dictionary<int,string>dt)
{
foreach (KeyValuePair<int,string>entry in dt)
{
MessageBox.Show(entry.Key.ToString()+entry.Value.ToString() + "eee");
}
}

2.3增查改删

//zd10-01

常用属性

count,Keys(键的集合,不允许重复),Values 值的集合

方法

增:

Add

//例

dict1.Add(1, "st1");

dict1.Add(2, "str1");

dict1.Add(3, "str2");

dict1.Add("KeysObject","ValuesObject");

//遍历

NavigateKeys(dict1);

删:

Remove,Clear

//删除键值为1的元素

dict1.Remove(1);//

dict1.Remove(11);//不存在,异常

dict1.Clear();

搜索:

Contains,ContainsKey,ContainsValue

bool bok =dict1.Contains(1);

bool bok = dict1.ContainsKey(1);

 bool bok = dict1.ContainsValue("str");

 其他 CopyTo  

原文地址:https://www.cnblogs.com/zoood/p/3618551.html