一.字典使用:
使用字典完成访问Ip次数统计:
Dictionary<string,int> map = new Dictionary<string,int>();
while (true)
{
Console.WriteLine("请输入IP地址");
string IP=Console.ReadLine();
//int value = 0;
if (map.ContainsKey(IP))
{
map[IP] +=1;
}
else
{
map[IP] = 1;
}
Console.WriteLine( "退出按1,再次访问按0" );
if (Console.ReadLine()=="1")
{
break;
}
}
foreach (string key in map.Keys)
{
Console.WriteLine($"输入IP:{key},访问次数:{map[key]}" );
}
执行结果:
请输入IP地址
162.1.1
退出按1,再次访问按0
0
请输入IP地址
162.1.1
退出按1,再次访问按0
0
请输入IP地址
162.1.1
退出按1,再次访问按0
1
输入IP:162.1.1,访问次数:3
二.List和字典混合使用:
求班级的学生数目,班级名称和班级平均年龄:
static void Main(string[] args)
{
//创建1班
List<student> list = new List<student>();
student S1 = new student() { name="张三",age=20 };
list.Add(S1);
student S2 = new student() { name = "李四", age = 30 };
list.Add(S2);
student S3 = new student() {name="王五",age=40 };
list.Add(S3);
//创建二班
List<student> list2 = new List<student>() {
new student(){name="王二",age=21 },
new student(){ name="李四",age=23},
new student(){ name="麻子",age=22}
};
Dictionary<string,List<student>> D1 = new Dictionary<string, List<student>>()
{
{ "一班",list},{ "二班",list2}
};
foreach (String Key in D1.Keys)
{
Console.WriteLine($"班级的名字:{Key},班级的学生数目:{D1[Key].Count}班级的平均年龄:{GetAveAge(D1[Key])}");
}
}
public static double GetAveAge(List<student> s)
{
int sum = 0;
foreach (student student in s)
{
sum+=student.age;
}
return sum*1.0/s.Count;
}
}
打印结果:
班级的名字:一班,班级的学生数目:3班级的平均年龄:30
班级的名字:二班,班级的学生数目:3班级的平均年龄:22
总结:由此可见,通过泛型方法,我们可以尽快的求取相应数据.