C# Dictionary 使用方法

 
  • using System;   
  • using System.Collections.Generic;   
  •   
  • class DictionaryDemo   
  • {   
  •     static void Main(string[] args)   
  •     {   
  •         DictionaryDemo001();   
  •         Console.ReadLine();   
  •   
  •         DictionaryDemo002();   
  •         Console.ReadLine();   
  •   
  •         DictionaryDemo003();   
  •         Console.ReadLine();   
  •     }   
  •   
  •     /// <summary>   
  •     /// 一般用法   
  •     /// </summary>   
  •     static void DictionaryDemo001()   
  •     {   
  •         Dictionary<intstring> dict = new Dictionary<intstring>();   
  •         dict.Add(1, "111");   
  •         dict.Add(2, "222");   
  •   
  •         //判断是否存在相应的key并显示   
  •         if (dict.ContainsKey(2))   
  •         {   
  •             Console.WriteLine(dict[2]);   
  •         }   
  •   
  •         //遍历Keys   
  •         foreach (var item in dict.Keys)   
  •         {   
  •             Console.WriteLine("Key:{0}", item);   
  •         }   
  •   
  •         //遍历Values   
  •         foreach (var item in dict.Values)   
  •         {   
  •             Console.WriteLine("value:{0}", item);   
  •         }   
  •   
  •         //遍历整个字典   
  •         foreach (var item in dict)   
  •         {   
  •             Console.WriteLine("key:{0} value:{1}", item.Key, item.Value);   
  •         }   
  •     }   
  •   
  •     /// <summary>   
  •     /// 参数为其它类型   
  •     /// </summary>   
  •     static void DictionaryDemo002()   
  •     {   
  •         Dictionary<stringstring[]> dict = new Dictionary<stringstring[]>();   
  •         dict.Add("1""1,11,111".Split(','));   
  •         dict.Add("2""2,22,222".Split(','));   
  •         Console.WriteLine(dict["2"][2]);   
  •     }   
  •   
  •     /// <summary>   
  •     /// 调用自定义类   
  •     /// </summary>   
  •     static void DictionaryDemo003()   
  •     {   
  •         Dictionary<int, yongfa365> dict = new Dictionary<int, yongfa365>();   
  •         for (int i = 0; i < 10; i++)   
  •         {   
  •             yongfa365 y = new yongfa365();   
  •             y.UserCode = i;   
  •             y.UserName = "www.yongfa365.com " + i.ToString();   
  •             dict.Add(i, y);   
  •         }   
  •         foreach (var item in dict)   
  •         {   
  •             Console.WriteLine("{0} One:{1} UserName:{2}", item.Key, item.Value.UserCode, item.Value.UserName);   
  •         }   
  •     }   
  • }   
  •   
  • class yongfa365   
  • {   
  •     public int UserCode { getset; }   
  •     public string UserName { getset; }   
  •   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值