c#基础加强--集合

怎样使用集合:

1、引用命名空间:System.Collections

2、使用ArrayList  (alt + shift + f10 自动引用)

ArrayList arrayList = new ArrayList();

3、arrayList.Add(object value) //object 可以接受任何类型的数据,包括数组。

EX: arrayList.Add(1);

       arrayList.Add("1");

4、arrayList.AddRange(ICollection c) //循环着将数组每项加入arrayList集合中

如:int[] nums={1,2,3,4,5}

       arrayList.AddRange(nums);//批量加入,将数组nums中每个值循环着一个一个的加入。此时,arrayList中有了五个成员。

arrayList.Add(nums);//只加入一项,将数组nums作为一个整体添加给了arrayList。此时,arrayList中只有1个成员。

5、arrayList.Clear();//清空arrayList集合的内容

6、 arrayList.Contains(object item)//判断arrayList中是否包含内容为item的项

7、arrayList.IndexOf(object value)

      arrayList.IndexOf(object value,int startIndex)

      arrayList.IndexOf(object value,int startIndex,int count);

8、arrayList.Insert(int index,object value);

9、arrayList.RemoveAt(int index);//删除集合中的某个位置

10、arrayList.Remove(object obj);//删除集合中的某个值

11、arrayList.Reverse();//将集合反序;

        arrayList.Reverse(int index,int count);

12、object[]  arrayList.ToArray()//将arrayList转换为object数组

       Array arrayList.ToArray(Type type) //将arrayList转换为某种类型的数组

       如果知道集合中存放是int类型数组,则:int[] n =(int) arrayList.ToArray(typeof(int));

       注意:有些时候需要使用类型信息,但是类型不是变量,无法作为参数。所以使用typeof(),可以讲类型名直接转为变量使用,如需要得到字符类型作为参数,就可以使用typeof(char)。此处,type 需要是集合arrayList中每项的类型,所以是typeof(int)。

       同时,此方法的返回值是Array,Array是数组的父类,可以将其强制转换为int类型。

13、arrayList[int index]//获取或者设置index索引位置的元素(从零开始索引)

Hashtable hashTable = new Hashtable() //根据关键字方便查找数据

1、hashTable.Add(object key,object value);//key 为关键字或者索引,索引对应的值,不能添加重复的KEY

2、hashTable.Contains(object key);

      hashTable.ContainsKey(object key);//与Contains功能相同

3、object hashTable["key"] //返回key关键字对应的在hashTable中的值,返回值为object,需要显示转换为对应的类型。

4、hashTable.clear() //清空hashTable中的内容

5、hashTable.Remove(object key);

6、foreach(var item in hashTable.Keys)//根据键值来遍历hashTable中的值

{

      Console.WriteLine(item);//item中保存了键值对应的值

}

foreach的运行原理:

  1.先到hashTable中,找到Keys集合

  2.使用in运算,在集合中下移一个位子

  3.里面有数据,将数据取出,赋值给item迭代变量

  4.开始执行循环体

  5.回到第2步,如果出现下移后数据不存在退出循环

ArrayList为线性表,Hashtable 为哈希表

泛型集合

空间名为:System.Collection.Generic

LIst<T> T代表为集合类型,等价于ArrayList集合

如:List<string> list = new List<string>();

       list.Add(string itme);//List<T> Add(T item)

Dictionary<TKey,TValue> 等价于Hashtable集合

如:Dictionary<string ,string> dic = new Dictionary<string,string>();

foreach本质:

GetEnumerator是一个IEnumerable接口返回的数据,类要实现foreach的遍历,则要实现此接口

pubic IEnumerator  GetEnumerato()

{

        //这里是迭代器

        yield return value;

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值