• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

norman

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

c#里面Dictionary的应用

引用命名空间System.Collection.Generic

Dictionary<string, string>是一个泛型

他本身有集合的功能有时候可以把它看成数组

他的结构是这样的:Dictionary<[key], [value]>

他的特点是存入对象是需要与[key]值一一对应的存入该泛型

通过某一个一定的[key]去找到对应的值

举个例子:

//实例化对象

Dictionary<int, string> dic = new Dictionary<int, string>();

//添加键

dic.Add(1, "one");

dic.Add(2, "two");

dic.Add(3, "one");

//提取元素的方法

string a = dic[1];

string b = dic[2];

string c = dic[3];

//查找键,使用ContainsValue

 if (dic.ContainsKey(1)) 
   {
      int p = dic[1];
      Console.WriteLine(p); 
  } 

//KeyNotFoundException

如果你尝试读取字典中一个不存在的键,那么你会得到一个KeyNotFoundException。所有在读取一个键之前,你必须先使用ContainKey来核对键是否存在字典中。 

//删除键

dic.Remove(); 

//1、2、3是键,分别对应“one”“two”“one”

//上面代码中分别把值赋给了a,b,c

//注意,键相当于找到对应值的唯一标识,所以不能重复

//但是值可以重复 

 

//遍历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);           }

 

foreach (KeyValuePair<string, string> pair in dic)
            {

                txt1.Text += string.Format("Key:{0}, Value:{1}\n", pair.Key, pair.Value);

            }

 

//排序 

using System;

using System.Collections.Generic;

using System.Text;

using System.Linq;

 

namespace DictionarySorting

{

class Program

{

static void Main(string[] args)

{

Dictionary<int, string> dic = new Dictionary<int, string>();

dic.Add(1, "HaHa");

dic.Add(5, "HoHo");

dic.Add(3, "HeHe");

dic.Add(2, "HiHi");

dic.Add(4, "HuHu");

 

var result = from pair in dic orderby pair.Key select pair;

 

foreach (KeyValuePair<int, string> pair in result)

{

Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);

}

 

Console.ReadKey();

}

}

}

 

【执行结果】

Key:1, Value:HaHa

Key:2, Value:HiHi

Key:3, Value:HeHe

Key:4, Value:HuHu

Key:5, Value:HoHo

posted on 2011-11-08 14:46  strgvi  阅读(179)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3