C#为用户提供了一种称为集合的新类型。集合类似于数组,是一组组合在一起的类型化对象,可以通过遍历来访问数组中的每个元素。.net提供实现集合的接口,包括IEnumberable,ICollection,Ilist等,只需继承实现集合接口。另外也可以直接使用.NET已经定义的一些集合类,包括Array、ArrayList、Quque、Stack、BitArrary、HashTable等。集合类的命名空间System.Collection提供。
数组的定义:
int [] score= new int[9];
集合定义:
ArrayList list= new ArrayList();
集合的基本信息:
1.BCL中集合类型分为泛型集合和非泛型集合。
2.非泛型集合的类和接口位于System.Collection命名空间。
3.泛型集合的类和接口位于System.Collection.Generic命名空间。
4.最常用的集合:
(1)ArrayList:
ArrayLis实现了Ilist、ICollection、IEnumberable接口。
ArrayList、Array:
相同点:
(a)两者实现了Ilist、ICollection、IEnumberable接口。
(2)Hashtable
实现了IDictionary、ICollection以及IEnumerable接口。注意Hashtable,t是小写的。由于是非泛型集合,因此存储进去的都是object类型,不管是键还是值。
Hashtable的要点。
(1)、Hashtable仅有非泛型版本。
(2)、Hashtable类中的键不允许重复,但值可以。
(3)、Hashtable类所存储的键值对中,值可以为null,但键不允许为null。
(4)、Hashtable不允许排序操作。
(5)DictionaryEntry :可设置或检索字典的键值对。
以下给出一个实例,Hashtable提供的功能是在于ArraryList差不多,只不过存储的是键值对而已。只写个基本短小的示例。
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1,"A");
ht.Add(2, "B");
ht.Add(3, "C");
ht.Add(4, "D");
ht.Add(5,"我爱你");
ht.Add(6, "我也爱你");
foreach (DictionaryEntry de in ht)
{
Console.WriteLine(de.Key);
Console.WriteLine(de.Value);
}
}
(3)Dictionary<string,string>;
需要两个类型参数。Dictionary<TKey, TValue>方法 说明
Add 将指定的键和值添加到字典中
Clear 从 Dictionary<TKey, TValue> 中移除所有的键和值。
ContainsKey 确定 Dictionary<TKey, TValue> 是否包含
ContainsValue 确定 Dictionary<TKey, TValue> 是否包含特定值。
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
GetEnumerator 返回循环访问 Dictionary<TKey, TValue> 的枚举器。
GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
tData 实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary 实例所需的数据。
GetType 获取当前实例的 Type。 (继承自 Object。)
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
OnDeserialization 实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
指定的键。
KeyValuePair<string ,string>:字典中可设置,检索字典的两个类型参数。
Remove 从 Dictionary<TKey, TValue> 中移除所指定的键的值。
ToString 返回表示当前对象的字符串。 (继承自 Object。)
TryGetValue 获取与指定的键相关联的值。
属性
Comparer 获取用于确定字
GetObjec典中的键是否相等的 IEqualityComparer<T>。
Count 获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。
Item 获取或设置与指定的键相关联的值。
Keys 获取包含 Dictionary<TKey, TValue> 中的键的集合。
Values 获取包含 Dictionary<TKey, TValue> 中的值的集合。
(原文:https://blog.youkuaiyun.com/a1256242238/article/details/72887731?utm_source=copy )
贴上小狸:
static void Main(string[] args)
{
Dictionary<string,string> dic = new Dictionary<string, string>();
dic.Add("111","aaa");
dic.Add("22", "b");
dic.Add("311", "ccc");
dic.Clear();
foreach (KeyValuePair<string ,string> d in dic)
{
Console.WriteLine(d.Key+d.Value);
}
foreach (string s in dic.Values)
{
Console.WriteLine(s);
}
}
5.列:
非泛型接口:ICollection、TList、IDictionary、IComparer、IEqualityComparer、IEnumerable、IEnumerator
泛型接口:ICollection<T>、TList<T>、IDictionary<T>、IComparer<T>、IEqualityComparer<T>、IEnumerable<T>、IEnumerator<T>
1327

被折叠的 条评论
为什么被折叠?



