《C#程序设计课件》(资料全集).ppt
第四章 数组和集合,C#.net程序设计,本章主要内容,集合类型接口IEnumerable、ICollection、IList和IDictionary数组Array、ArrayList和List泛型类Hashtable类和Dictionary泛型类SortedList和SortedList泛型类队列Queue类和Queue泛型类,堆栈Stack类和Stack 泛型类,集合类型概述,集合通常可以分为常用集合,专用集合等类型:常用集合。常用集合有泛型和非泛型之分。非泛型集合是以Object 类型为元素集合,如哈希表Hashtable、队列Queue、堆栈Stack、和列表ArrayList,。泛型集合类型是非泛型类型的直接模拟。泛型集合包含ArrayList的泛型版List,Hashtable的泛型版Dictionary集合等。专用集合。这些集合都具有专门的用途,通常用于处理特定的元素类型,如 StringDictionary是将键和值强类型化为字符串而不是Object来实现Hashtable集合类型。,集合类型,IEnumerable接口,集合是基于IEnumerable接口、ICollection接口、IList接口、IDictionary接口,或其泛型集合中的相应接口,而IEnumerable接口、ICollection接口是大部分集合类所共同实现的。下面分别介绍IEnumerable接口、ICollection接口。第一种集合是实现IEnumerable接口的集合类,IEnumerable接口只有一个公共方法:IEnumerator GetEnumerator()该方法返回一个用于foreach简单迭代循环访问集合的枚举数。所有实现了IEnumerable接口的集合类如数组Array,ArrayList集合类型等都可以用于foreach循环语句。IEnumerator接口的成员如下表。,集合类型,ICollection 接口,ICollection 接口继承IEnumerable接口,除了继承IEnumerable接口成员外,还有下表所示的成员。,集合类型,List 接口,List 接口表示可按照索引单独访问的对象的非泛型集合接口。IList 接口继承了ICollection接口和IEnumerable接口,IList是所有非泛型列表的基接口。IList接口的公共属性与方法 如下表:,数组Array、ArrayList和List泛型类,数组Array类,Array 类是所有数组的基类,提供创建、操作、搜索和排序数组的方法,Array 类定义语法如下:public abstract class Array:ICloneable,IList,ICollection,IEnumerable。因此Array类实现IList,ICollection,IEnumerable,ICloneable接口,也就是说,Array类实现了这些接口的方法成员。Array类除了Copy,CopyTo外其它常用的方法:Array.Clear方法:public static void Clear(Array array,int index,int length)Array.Clone方法是实现ICloneable接口的方法,Clone方法创建数组Array的浅表副本,数组的浅表副本仅复制数组的元素(无论它们是引用类型还是值类型),但不复制这些引用所引用的对象。新数组中的引用与原始数组中的引用指向相同的对象。数组使用Copy,CopyTo方法复制的也是浅表副本。所以这三个复制方法得到的复制的副本都是一样。,数组Array、ArrayList和List泛型类,public class Studentpublic string Name;public Student(string Name)this.Name=Name;public class CloneCopyArraypublic static void Main()Student stu0=new Student(student1);Student stu1=new Student(student2);Student stu2=new Student(student3);Student arrStu=new Student stu0,stu1,stu2;Student arrStuClone=(Student)arrStu.Clone();/克隆数组Student arrStuCopy=new StudentarrStu.Length;Array.Copy(arrStu,arrStuCopy,arrStu.Length);/拷贝数组Console.WriteLine(原来数组内容);PrintIndexAndValues(arrStu);Console.WriteLine(克隆数组内容:);PrintIndexAndValues(arrStuClone);Console.WriteLine(改变克隆数组内容之前);,例:演示数组Array的Copy和Clone方法的使用,CloneCopyArray项目代码:,Console.WriteLine(arrStu2.Name:0,arrStu2.Name);Console.WriteLine(arrStuClone2.Name:0,arrStuClone2.Name);Console.WriteLine(arrStuCopy2.Name:0,arrStuCopy2.Name);arrStuClone2.Name=student2CloneNew;/arrStuCopy2.Name=student2CopyNew;Console.WriteLine(改变克隆数组内容之后);Console.WriteLine(arrStu2.Name:0,arrStu2.Name);Console.WriteLine(arrStuClone2.Name:0,arrStuClone2.Name);Console.WriteLine(arrStuCopy2.Name:0,arrStuCopy2.Name);public static void PrintIndexAndValues(Array myArray)for(int i=myArray.GetLowerBound(0);i=myArray.GetUpperBound(0);i+)Console.WriteLine(t0:t1,i,myArray.GetValue(i);arrStuClone是使用clone方法复制的student类对象数组,arrStuCopy是使用copy方法复制的student类对象数组,由于它们都是复制的浅表副本,所以在三个数组的引用都指向相同的student类对象数组。,ArrayList 类,Array用作所有数组的基类,而ArrayList是较为复杂的数组。ArrayList 类和Array 类一样都实现IList,ICollection,IEnumerable,ICloneable接口。ArrayList类除了所实现的IList,ICollection,IEnumerable,ICloneable接口的方法成员,还包含下面主要属性和方法:,使用ArrayList类Add、AddRange和ToArray方法的项目ArrayListSample代码:using System;using System.Collections;public class SamplesArrayList public static void Main()ArrayList myAL=new ArrayList();/创建和初始化ArrayList.myAL.Add(The);/添加一个元素 myAL.AddRange(new string quick,brown,fox,jumped,over,the,lazy,dog);/添加一组元素 PrintIndexAndValues(myAL);/显示ArrayList的值 String myArr=(String)myAL.ToArray(typeof(string);/将元素复制数组 PrintIndexAndValues(myArr);/显示数组内容 public static void PrintIndexAndValues(ArrayList myList)int i=0;foreach(Object o in myList)Console.Write(t0:t1,i+,o);public static void PrintIndexAndValues(String myArr)for(int i=0;i myArr.Length;i+)Console.Write(t0:t1,i,myArri);,List 泛型类,List 泛型类是 ArrayList 类的泛型等效类,表示可通过索引访问的强类型列表。所谓的强类型,是指创建列表List时指定集合类型,而不是ArrayList的object集合类型,这样对于值类型的List泛型类来说,无需装箱和取消装箱或转换。ListTSample项目的代码示例演示 List 泛型类:using System;using System.Collections.Generic;public class Example public static void Main()/创建string的List泛型实例,创建列表时指定集合类型为string List dinosaurs=new List();Console.WriteLine(nCapacity:0,dinosaurs.Capacity);/显示List容量 dinosaurs.Add(Tyrannosaurus);/向List添加 dinosaurs.Add(Amargasaurus);dinosaurs.Add(Mamenchisaurus);dinosaurs.Add(Deinonychus);,dinosaurs.Add(Compsognathus);foreach(string dinosaur in dinosaurs)Console.WriteLine(dinosaur);Console.WriteLine(nCapacity:0,dinosaurs.Capacity);Console.WriteLine(Count:0,dinosaurs.Count);Console.WriteLine(nContains(Deinonychus):0,dinosaurs.Contains(Deinonychus);/判断列表是否包含Deinonychusdinosaurs.Insert(2,Compsognathus);/在位置插入Compsognathus“foreach(string dinosaur in dinosaurs)Console.WriteLine(dinosaur);Console.WriteLine(ndinosaurs3:0,dinosaurs3);/使用位置索引dinosaurs.Remove(Compsognathus);/删除Compsognathusforeach(string dinosaur in dinosaurs)Console.WriteLine(dinosaur);dinosaurs.TrimExcess();/根据集合数量缩减容量Console.WriteLine(nTrimExcess()nCapacity:0,dinosaurs.Capacity);Console.WriteLine(Count:0,dinosaurs.Count);dinosaurs.Clear();/清空Console.WriteLine(nClear()nCapacity:0,dinosaurs.Capacity);Console.WriteLine(Count:0,dinosaurs.Count);,List 泛型类,代码分析:使用默认构造函数创建一个空的字符串类型的List泛型列表。随后显示 Capacity 属性,然后使用 Add 方法添加若干个项。添加的项被列出,Capacity 属性会同 Count 属性一起再次显示,指示已根据需要增加了容量。使用 Contains 方法测试该列表中是否存在某个项,使用 Insert 方法在列表的中间插入一个新项,然后再次显示列表的内容。默认的 Item 属性(C#中的索引器)用于检索项,Remove 方法用于移除前面添加的重复项的第一个实例,然后,该示例再次显示内容。Remove 方法总是移除它所遇到的第一个实例。使用 TrimExcess 方法减小容量以匹配计数,然后显示 Capacity 和 Count 属性。如果未用容量已经小于总容量的 10%,则列表容量不会进行调整。使用 Clear 方法移除列表中的所有项,并显示 Capacity 和 Count 属性。,数组Array、ArrayList和List泛型类,List,ArrayList 类与Array数组的区别:,Array 的容量是固定的,而 ArrayList的容量可根据需要自动扩充。如果更改了 Capacity 属性的值,则可以自动进行内存重新分配和元素复制。ArrayList提供添加、插入或移除某一范围元素的方法。在 Array 中,只能一次获取或设置一个元素的值。使用 Synchronized 方法很容易创建 ArrayList 的同步版本。Array 将实现同步的任务留给了用户。ArrayList提供将只读和固定大小包装返回到集合的方法;而 Array 不提供。可以设置 Array 的下限,但 ArrayList的下限始终为零。Array 可以具有多个维度,而 ArrayList始终只是一维的。特定类型(不包括Object)的数组Array的性能优于ArrayList,这是因为ArrayList的元素属于Object类型,所以在存储或检索值类型时通常发生装箱和取消装箱操作。不过,在不需要重新分配时(即最初的容量十分接近列表的最大容量),List泛型类的性能与同类型的数组十分相近。需要数组的大多数情况都可以改为使用ArrayList或List泛型类;它们更容易使用,并且一般与相同类型的数组具有相近的性能。尽量使用List类,而不是使用ArrayList类或自己编写强类型包装集合。,数组Array、ArrayList和List泛型类,Hashtable、Dictionary和SortedList集合类,Hashtable、Dictionary和SortedList集合类都实现IDictionary,ICollection,IEnumerable,ICloneable接口。其中IDictionary接口表示键/值对的集合接口,或者说Hashtable、Dictionary和SortedList都是关于键/值对的集合。IDictionary接口是键/值对的非通用集合的基接口。每个元素都是一个存储在 DictionaryEntry对象中的键/值对。IDictionary接口继承了ICollection,IEnumerable接口,除了ICollection,IEnumerable接口成员外,还有以下成员:,IDictionary接口成员,using System.Collections;/使用Hashtable类的项目HashtableSample的代码:public class SamplesHashtable public static void Main()Hashtable ht=new Hashtable();/创建Hashtable实例ht ht.Add(N01,张三);/添加将带有指定键和值的元素添加到ht ht.Add(N02,李四);ht.Add(N03,王五);Console.WriteLine(ht:Count:0,ht.Count);/显示Hashtable的属性Count PrintKeysAndValues(ht);public static void PrintKeysAndValues(Hashtable ht)foreach(DictionaryEntry de in ht)/显示Hashtable的键和值 Console.Write(0,1),de.Key,de.Value);使用Hashtable的Add(Objectkey,Objectvalue)方法集合添加元素。Hashtable的元素是一个键/值对,元素类型既不是键的类型,也不是值的类型,而是DictionaryEntry类型,因此foreach循环语句使用foreach(DictionaryEntryde in ht)。DictionaryEntry是结构类型,具有object类型的键属性Key和object类型的值属性Key。,使用Dictionary泛型类DictionarySample项目代码:,public class Sample public static void Main()/创建键和值都为string的dictionary对象实例openWith.Dictionary openWith=new Dictionary();/为dictionary实例openWith添加元素,其中键值唯一,有些值是重复的 openWith.Add(txt,notepad.exe);openWith.Add(bmp,paint.exe);openWith.Add(dib,paint.exe);openWith.Add(rtf,wordpad.exe);try/插入具有重复键的元素因起异常 openWith.Add(txt,winword.exe);catch(ArgumentException)Console.WriteLine(An element with Key=txt already exists.);/使用键索引得到其值 Console.WriteLine(For key=rtf,value=0.,openWithrtf);openWithrtf=winword.exe;/使用键索引设置其值 Console.WriteLine(For key=rtf,value=0.,openWithrtf);openWithdoc=winword.exe;/如果该键不存在,添加新key/value元素,try/如果没有该键,取其值引起异常 Console.WriteLine(For key=tif,value=0.,openWithtif);catch(KeyNotFoundException)Console.WriteLine(Key=tif is not found.);string value=;if(openWith.TryGetValue(tif,out value)/该方法更有效,不引起异常Console.WriteLine(For key=tif,value=0.,value);else Console.WriteLine(Key=tif is not found.);if(!openWith.ContainsKey(ht)/判断是否含有该键 openWith.Add(ht,hypertrm.exe);Console.WriteLine(Value added for key=ht:0,openWithht);foreach(KeyValuePair kvp in openWith)/遍历该字典Console.WriteLine(Key=0,Value=1,kvp.Key,kvp.Value);/取该字典值属性,值集合ValueCollection是强类型集合(本例string类型)Dictionary.ValueCollection valueColl=openWith.Values;foreach(string s in valueColl)/遍历该字典值集合ValueCollectionConsole.WriteLine(Value=0,s);,/取该字典的键属性,键集合KeyCollection是强类型集合(本例string类型)Dictionary.KeyCollection keyColl=openWith.Keys;foreach(string s in keyColl)/遍历该字典键集合ValueCollection Console.WriteLine(Key=0,s);Console.WriteLine(n删除键为(doc)的这对元素);openWith.Remove(doc);if(!openWith.ContainsKey(doc)Console.WriteLine(Key doc is not found.);代码分析:使用Item属性(即索引器)来检索值,当请求的键不存在时将引发KeyNotFoundException,与键相关联的值可被替换。当程序必须经常尝试字典中不存在的键值时,使用TryGetValue方法作为一种更有效的方法来检索值,使用ContainsKey方法在调用Add方法之前测试某个键是否存在。使用Keys属性和Values属性来单独枚举键和值。使用Remove方法删除集合中的一个元素。,Queue类和Queue泛型类,Queue类和Queue泛型类都是先进先出集合类,它们实现IEnumerable、ICollection和ICloneable等接口,Queue泛型类还实现了IEnumerable和ICollection泛型接口。队列在按接收顺序存储消息方面可以方便地进行顺序处理。此类将队列作为循环数组实现。存储在Queue中的对象在一端插入,从另一端移除。Queue接受空引用作为有效值并且允许重复的元素。可以对Queue及其元素执行三种主要操作:Enqueue将一个元素添加到Queue的末尾。Dequeue从Queue的开始处移除最旧的元素。Peek从Queue的开始处返回最旧的元素,但不将其从Queue中移除。下面是使用队列Queue泛型类的QueueSample项目的代码:,using System.Collections.Generic;class Example public static void Main()Queue numbers=new Queue();numbers.Enqueue(one);numbers.Enqueue(two);numbers.Enqueue(three);numbers.Enqueue(four);numbers.Enqueue(five);foreach(string number in numbers)Console.WriteLine(number);Console.WriteLine(nDequeuing 0,numbers.Dequeue();Console.WriteLine(Peek at next item:0,numbers.Peek();Console.WriteLine(Dequeuing 0,numbers.Dequeue();/使用 ToArray 方法将队列元素复制到数组,然后将该数组/传递给接受 IEnumerable 的 Queue 构造函数以创建队列副本 Queue queueCopy=new Queue(numbers.ToArray();foreach(string number in queueCopy)Console.WriteLine(number);,/创建一个大小是队列大小两倍的数组 string array2=new stringnumbers.Count*2;/使用 CopyTo 方法从数组中间开始复制数组元素 numbers.CopyTo(array2,numbers.Count);/使用接受IEnumerable 的Queue 构造函数创建第二个队列 Queue queueCopy2=new Queue(array2);foreach(string number in queueCopy2)Console.WriteLine(number);Console.WriteLine(nqueueCopy.Contains(four)=0,queueCopy.Contains(four);queueCopy.Clear();Console.WriteLine(nqueueCopy.Count=0,queueCopy.Count);,使用 Enqueue 方法将五个字符串加入队列进行排队。使用 Dequeue 方法使第一个字符串出列。使用 Peek 方法查找队列中的下一项。使用 ToArray 方法创建一个数组并将队列元素复制到该数组,然后将该数组传递给接受 IEnumerable 的 Queue 构造函数以创建队列副本,并显示副本的元素。创建一个大小是队列大小两倍的数组,并使用CopyTo方法从数组中间开始复制数组元素。使用 Contains 方法显示字符串“four”在第一个队列副本中,然后使用 Clear 方法清除此副本,并由 Count 属性显示该队列为空。,堆栈Stack 类和 Stack 泛型类,堆栈集合类型Stack类和Stack泛型类都是后进先出集合类,它们实现IEnumerable、ICollection和ICloneable等接口,Stack泛型类还实现了IEnumerable和ICollection泛型接口。可以使用堆栈和队列存储临时信息,如果需要按照信息存储在集合中的顺序来访问这些信息,使用队列Queue。如果需要以相反的顺序访问这些信息,使用堆栈Stack。Stack常用于在调用其他过程期间保留变量状态。可以对Stack及其元素执行三种主要操作:Push可在Stack的顶部插入一个元素。Pop可在Stack的顶部移除一个元素。Peek可返回处于Stack顶部的元素,但不将其从Stack上移除。,class Example public static void Main()Stack numbers=new Stack();numbers.Push(one);numbers.Push(two);foreach(string number in numbers)Console.WriteLine(number);Console.WriteLine(nPopping 0,numbers.Pop();Console.WriteLine(Peek at next item:0,numbers.Peek();/使用 ToArray 方法创建数组并将堆栈元素复制到其中,/然后将数组传递给具有 IEnumerable 的 Stack 构造函数.Stack stack2=new Stack(numbers.ToArray();foreach(string number in stack2)Console.WriteLine(number);Console.WriteLine(stack2.Contains(four)=0,stack2.Contains(four);stack2.Clear();Console.WriteLine(nstack2.Count=0,stack2.Count);,用堆栈Stack泛型类的几个方法。下面是StackSample项目的代码:,