C#总结(三)
2015-12-13 17:42
405 查看
前言:
泛型是C#2.0的一个新增加的特性,是C#编程中不可缺少的部分。它是程序设计语言的一种特性,为使用C#语言编写面向对象程序增加了极大的效力和灵活性。集合--ArrayList():
ArrayList():可以放各种类型的数据,并且不确定放多少个。可以把集合看作为“长度可变的,具有很多方法的数组”集合常用的方法:
1)arrayList.Clear():清空2)arrayList.Contains():判断这个集合中是否包含这个元素;
3)arrayList.Count():集合中元素的个数;
4)arrayList.indexOf():找某个元素对应的索引;
5)arrayList.InsertRange(n,nums):往某个索引位置插入一个数组;
6)arrayList.Remove():直接删除指定的元素;
7)arrayList.RemoveAt():移除索引对应的值;
8)arrayList.RemoveRanges(n,m):从指定索引处开始移除,移除多少个,如果超出索引报异常;
9)arrayList.Add():插入
10)arrayList.Reverse():反转;
11)arrayList.Sort():排序;
12)ToArray:复制到另外一个数组中;
集合插入数据的3种方式:
1)通过构造函数可以添加一个数组;2)通过Add()方法可以添加数组,但算成一个元素;
3)通过AddRange()可以添加数组;
哈希表:
无序的,不能添加相同的键。以键值对的形式存值,key-—键,value—值。
foreach():遍历哈希表
remove:将key移除,值也没有了。
泛型集合:
List<T>为了专门处理某种类型。ArrayList对应的是List<类型名>,在尖括号中写什么类型,这个集合就变成了什么类型的集合。添加数据、插入数据、索引访问数据都是这个类型的,不用考虑所有的转化问题。List()常用方法:
list.Count--个数、list.Cantains()--包含、list.Add()--添加、list.Max()--最大值、list.Min()--最小值、list.Sum()--和、list.Avgerage()--平均值、list.Clear()--移除所有元素、list.Equals()--比较。应用:
using System.Text; namespace _泛型集合 { class Program { static void Main(string[] args) { List<int> list = new List<int>(); //随机的往这个List集合中添加十个数字,不能重复,求和 求最大值,求最小值,求平均值 Random r = new Random(); int num = 0; while (list.Count!=10) { num = r.Next(1, 100); if (!list.Contains(num)) { list.Add(num); } } Console.WriteLine("最大值:{0}",list.Max()); Console.WriteLine("最小值{0}",list.Min()); Console.WriteLine("和为{0}",list.Sum()); Console.WriteLine("平均值{0}",list.Average()); Console.ReadKey();
Dictionary:
Dictionary<TKey,TValue>,默认提供命名空间,提倡使用;Hashtable对应的是Dictionary<键的类型,值的类型>,在尖括号中填入键的类型与值得类型,那么这个集合就变成了一个指定的键值对模型,其使用方式与Hashtable一样。namespace _04字典 { class Program { static void Main(string[] args) { Dictionary<string, string> dic = new Dictionary<string, string>(); //和哈希表很像 也是无序的 dic.Add("老苏","凤姐"); dic.Add("老牛","芙蓉姐姐"); dic.Add("老马", "春哥"); dic.Add("老虎", "曾哥"); dic.Add("老蒋","小月月"); foreach (string item in dic.Keys) { Console.WriteLine("key---:{0},value---:{1}",item,dic[item]); } Console.ReadKey();