C#集合和泛型-List,dictionary&LinkedList

一.字典使用:

使用字典完成访问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

总结:由此可见,通过泛型方法,我们可以尽快的求取相应数据.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值