前言
今天学到了泛型集合和字典,都是一些新知识,所以进行了总结,和大家分享一下!
分享
- List :(T是type的缩写,代表类型)T也可以写成其他的,只不过是一个代号而已
- ①不用导入命名空间,ArrayList需要导入命名空间
- ②处理某种类型,ArrayList对应的是List<类型名>,(尖括号中写什么类型,集合就变成了什么类型的集合,添加数据、插入数据、索引访问数据都是这个类型的,不用考虑所有的转化问题)
- 示例:
namespace _02泛型集合
{
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);//从1到99
if(!list.Contains (num))
{
list.Add(num);
}
}
Console.WriteLine("最大值:{0},最小值:{1},和为:{2},平均值为:{3}", list.Max(), list.Min(), list.Sum(), list.Average());
//Console.WriteLine("最小值:{0}",list.Min());
//Console.WriteLine("和为:{0}",list.Sum());
//Console.WriteLine("平均值为:{0}",list.Average ());
Console.ReadKey();
}
}
}
- 字典:
- 简介:让我们可以通过索引号查询到特定数据的数据结构类型
- 关键字:Dictionary
- 用处:平时情况下,我们可以通过索引从数组或者是list中查询需要的数据,如果复杂一些的话:索引号是非int类型的,这时候不容易查,就可以用字典了。
Dictionary<TKey,TValue>
- ①默认提供命名空间,提倡使用
- ②Hashtable对应的是 Dictionary<键的类型,值的类型>
- ③在尖括号中填入键的类型与值的类型,则集合集合变成了指定的键值对模型,使用方式和Hashtable一样
- 示例:
namespace _03字典
{
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)//遍历key
{
Console.WriteLine("key---:{0},value---:{1}",item,dic[item]);
}
Console.ReadKey();
}
}
}
- 补充:
- a.遍历所有:
foreach(KeyValuePair<string,string> stu in students)
Debug.Log ("Key:"+stu.Key+" Name:"+stu.Value);
- b.遍历value:
foreach (string value in students.Values)
Debug.Log (value);
- c.删除:
dic.Remove ("S000");
- d.修改:
dic["S002"]="李斯";
- e.查询:
Debug.Log (dic["S000"]);
小结
这是我对这一部分内容的理解,这只是自己的想法,希望大家多多指正,在评论下方留言就可以了,谢谢!!!