泛型集合及字典集合理解

来源:互联网 发布:自学电吉他 知乎 编辑:程序博客网 时间:2024/06/07 11:56

1.在ArrayList集合集合中,集合中的数据比较杂乱,导致无法有效地遍历出所有的数据,因此,我们引进泛型集合,将ArrayList集合使用为有类型的集合。
泛型集合的特点:
1)完整的提高了用户的数据统一性;可以无止修存数据;
2)泛型可以转换为对应类型的数组;
用法如下:
List < Type > list=new List < Type >( );
以下是通过代码进行解释:

            List<int> list=new List<int>();//申明泛型对象            list.Add(1);//增加整形元素            list.Add(2);            for (int i = 0; i < list.Count; i++)            {                Console.WriteLine(list[i]);            }

打印出1 2

List< int >中常用的函数:
1、list.Add函数:向集合中增加单个元素;

2、list.AddRange函数:向集合中增加数组或者是泛型集合;
示例代码如下:
1.数组为例

            List<int> list=new List<int>();//申明泛型对象            list.AddRange(new int[]{3,4,5,6,7,8,9});//添加数组并将其放入集合中

2.泛型集合为例:

            List<int> list=new List<int>();//申明泛型对象            list.Add(1);//增加整形元素            list.Add(2);            List<int> lists = new List<int>();            lists.Add(1);            lists.Add(2);            list.AddRange(lists);//将lists中集合数据放入到list中;

打印结果为1 2 1 2
注明:他可以将其他泛型集合中的数据放入到本集合中,他们集合中的数据并不影响;

4.泛型集合转换为数组元素

            int[] num = list.ToArray();//将泛型集合中的元素转换为数组

5.当然,数组可以转换为泛型集合,那么泛型集合中元素可以转换为数组;
如代码所示:

            List<int> listf = (new int[]{1,2,4,4}).ToList();//将数组转换为泛型集合

二、我们知道,可以使用Hashtable类根据键值可以找到相应的值,但是,与上述一样,数据类型的不统一,使得集合中的数据变得有些混乱,无法清晰的取出数据,因此,我们引用了Dictionary< Type,Type >来添加指定类型的集合;

用法为:Dictionary< Type ,Type > dic=new Dictionary< Type ,Type >( );
代码如下:

            Dictionary<int, string> dic = new Dictionary<int, string>();            dic.Add(1, "Green");//添加元素            dic.Add(2, "Blach");            dic.Add(3, "Tom");            foreach (var item in dic.Keys)//遍历集合中数据            {                Console.WriteLine("{0}---------------{1}",item,dic[item]);            }

执行结果如下:
1———————-Green
2———————-Blach
3———————-Tom

附加点:对于遍历这一块,我们可以使用KeyValuePair< Type,Type >来遍历;
代码如下:

            foreach (KeyValuePair<int,string> kv in dic)//KeyValuePair< Type,Type >键值对遍历            {                Console.WriteLine("{0}----------{1}", kv.Key, kv.Value);                //kv.Key 获取键值   kv.Value获取值            }

打印结果:
1———————-Green
2———————-Blach
3———————-Tom

0 0
原创粉丝点击