c#里面Dictionary超级用法和实用_第1页
c#里面Dictionary超级用法和实用_第2页
c#里面Dictionary超级用法和实用_第3页
c#里面Dictionary超级用法和实用_第4页
c#里面Dictionary超级用法和实用_第5页
已阅读5页,还剩5页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、= false)                    pList.Add("Item3", "BeiJiang");                    &

2、#160;    catch (System.Exception e)            Console.WriteLine("Error: 0", e.Message);            /判断是否存在相应的key并显示    if

3、60;(pList.ContainsKey("Item1")            Console.WriteLine("Output: " + pList"Item1");         /遍历Key    foreach (var key in 

4、;pList.Keys)            Console.WriteLine("Output Key: 0", key);         /遍历Value    foreach (String value in pList.Values)     &#

5、160;      Console.WriteLine("Output Value: 0", value);        /遍历Key和Value    foreach (var dic in pList)            Console.W

6、riteLine("Output Key : 0, Value : 1 ", dic.Key, dic.Value);    2、用法2:Dictionary的Value为一个数组/ <summary>/ Dictionary的Value为一个数组/ </summary> public static void DicSample2()      Dictionary<String, String> d

7、ic = new Dictionary<String, String>();     String ZheJiang =  "Huzhou", "HangZhou", "TaiZhou"      String ShangHai = "Budong", "Buxi"      dic.Add(&q

8、uot;ZJ", ZheJiang);     dic.Add("SH", ShangHai);     Console.WriteLine("Output :" + dic"ZJ"0); 3、用法3: Dictionary的Value为一个类/Dictionary的Value为一个类public static void DicSample3()  

9、0;   Dictionary<String, Student> stuList = new Dictionary<String, Student>();     Student stu = null;     for (int i = 0; i < 3; i+ )            

10、  stu = new Student();         stu.Name = i.ToString();         stu.Name = "StuName" + i.ToString();         stuList.Add(i.ToString(),

11、stu);           foreach (var student in stuList)              Console.WriteLine("Output : Key 0, Num : 1, Name 2", student.Key, student.Value.Name, st

12、udent.Value.Name);      Student类:public class Student    public String Num get; set;     public String Name get; set;  4 备注:Dictionary的扩展方法使用 / <summary>/ Dictionary的扩展方法使用/ </summary>

13、0;public static void DicSample4()      /1)普通调用     Dictionary<int, String> dict = new Dictionary<int, String>();     DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan");&#

14、160;    DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu");     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu");     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu"

15、);     DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi");      /2)TryAdd 和 AddOrReplace 这两个方法具有较强自我描述能力,用起来很省心,而且也简单:     dict.AddOrPeplace(20, "Orange");     dict.TryAdd

16、(21, "Banana");     dict.TryAdd(22, "apple");      /3)像Linq或jQuery一样连起来写        dict.TryAdd(10, "Bob")         .TryAdd(11, "Tom&qu

17、ot;)         .AddOrPeplace(12, "Jom");      /4) 获取值     String F = "Ba"     dict.TryGetValue(31, out F);     Console.WriteLin

18、e("F : 0",F);      foreach (var dic in dict)              Console.WriteLine("Output : Key : 0, Value : 1", dic.Key, dic.Value);      &#

19、160;   /5)下面是使用GetValue获取值     var v1 = dict.GetValue(111,null);     var v2 = dict.GetValue(10,"abc");      /6)批量添加     var dict1 = new Dictionary<

20、int,int>();     dict1.AddOrPeplace(3, 3);     dict1.AddOrPeplace(5, 5);      var dict2 = new Dictionary<int, int>();     dict2.AddOrPeplace(1, 1);     

21、dict2.AddOrPeplace(4, 4);     dict2.AddRange(dict1, false); 扩展方法所在的类public static class DictionaryExtensionMethodClass     / <summary>    / 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常    / </summ

22、ary>    public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)            if (dict.ContainsKey(key) = false) 

23、           dict.Add(key, value);        return dict;         / <summary>    / 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换   

24、60;/ </summary>    public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)            dictkey = value; 

25、60;      return dict;         / <summary>    / 获取与指定的键相关联的值,如果没有则返回输入的默认值    / </summary>    public static TValue GetValue<TKey, TValue

26、>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)            return dict.ContainsKey(key)?dictkey : defaultValue;         / <summary>   

27、 / 向字典中批量添加键值对    / </summary>    / <param name="replaceExisted">如果已存在,是否替换</param>    public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue

28、> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)            foreach (var item in values)               

29、;     if (dict.ContainsKey(item.Key) = false | replaceExisted)                dictitem.Key = item.Value;             

30、60;  return dict;      Dictionary<string, string>是一个泛型他本身有集合的功能有时候可以把它看成数组他的结构是这样的:Dictionary<key, value>他的特点是存入对象是需要与key值一一对应的存入该泛型通过某一个一定的key去找到对应的值举个例子:复制代码代码如下:/实例化对象Dictionary<int, string> dic = new Dictionary<int, string>();/

31、对象打点添加dic.Add(1, "one");dic.Add(2, "two");dic.Add(3, "one");/提取元素的方法string a = dic1;string b = dic2;string c = dic3;/1、2、3是键,分别对应“one”“two”“one”/上面代码中分别把值赋给了a,b,c/注意,键相当于找到对应值的唯一标识,所以不能重复/但是值可以重复如果你还看不懂我最后给你举一个通俗的例子有一缸米,你想在在每一粒上都刻上标记,不重复,相当于“键”当你找的时候一一对应不会找错,这就是这个泛型的键的-

32、作用,而米可以一样,我的意思你明白了吧?-c# 对dictionary类进行排序用什么接口实现 如果使用.Net Framework 3.5的话,事情就很简单了。呵呵。如果不是的话,还是自己写排序吧。 复制代码代码如下:using System;using System.Collections.Generic;using System.Text;using System.Linq;namespace DictionarySortingclass Programstatic void Main(string args)Dictionary<int, string>

33、 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>

34、pair in result)Console.WriteLine("Key:0, Value:1", pair.Key, pair.Value); Console.ReadKey();【执行结果】复制代码代码如下:Key:1, Value:HaHaKey:2, Value:HiHiKey:3, Value:HeHeKey:4, Value:HuHuKey:5, Value:HoHoDictionary的基本用法。假如需求:现在要导入一批数据,这些数据中有一个称为公司的字段是我们数据库里已经存在了的,目前我们需要把每个公司名字转为ID后才存入数据库。分析:每导一笔记

35、录的时候,就把要把公司的名字转为公司的ID,这个不应该每次都查询一下数据库的,因为这太耗数据库的性能了。解决方案:在业务层里先把所有的公司名称及相应的公司ID一次性读取出来,然后存放到一个Key和Value的键值对里,然后实现只要把一个公司的名字传进去,就可以得到此公司相应的公司ID,就像查字典一样。对,我们可以使用字典Dictionary操作这些数据。示例:SetKeyValue()方法相应于从数据库里读取到了公司信息。复制代码代码如下:/ <summary>/ 定义Key为string类型,Value为int类型的一个Dictionary/ </summary>/

36、<returns></returns>protected Dictionary<string, int> SetKeyValue()Dictionary<string, int> dic = new Dictionary<string, int>();dic.Add("公司1", 1);dic.Add("公司2", 2);dic.Add("公司3", 3);dic.Add("公司4", 4);return dic;/ <summary>/ 得到

37、根据指定的Key行到Value/ </summary>protected void GetKeyValue()Dictionary<string, int> myDictionary = SetKeyValue();/测试得到公司2的值int directorValue = myDictionary"公司2"Response.Write("公司2的value是:" + directorValue.ToString();     在C#中,Dictionary提供快速的基于兼职的元素查找。他的

38、结构是这样的:Dictionary<key, value> ,当你有很多元素的时候可以使用它。它包含在System.Collections.Generic名空间中。在使用前,你必须声明它的键类型和值类型。方法/步骤1.  要使用Dictionary集合,需要导入C#泛型命名空间 System.Collections.Generic(程序集:mscorlib)2.  Dictionary的描述1、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成2、任何键都必须是唯一的3、键不能为空引用null(VB中的Nothi

39、ng),若值为引用类型,则可以为空值4、Key和Value可以是任何类型(string,int,custom class 等)3.  Dictionary常用用法:以 key 的类型为 int , value的类型为string 为例 1、创建及初始化 Dictionary<int,string>myDictionary=newDictionary<int,string>();  2、添加元素myDictionary.Add(1,"C#");myDictionary.Add(2,"C+&qu

40、ot;);myDictionary.Add(3,"ASP.NET");myDictionary.Add(4,"MVC");  3、通过Key查找元素if(myDictionary.ContainsKey(1)Console.WriteLine("Key:0,Value:1","1", myDictionary1);   4、通过KeyValuePair遍历元素foreach(KeyValuePair<int,string>kvp in myDiction

41、ary).Console.WriteLine("Key = 0, Value = 1",kvp.Key, kvp.Value); 5、仅遍历键 Keys 属性Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;foreach(intkeyinkeyCol).Console.WriteLine("Key = 0", key); 6、仅遍历值 Valus属性Dictionary<int,string>.ValueCollection value

42、Col=myDictionary.Values;foreach(stringvalueinvalueCol).Console.WriteLine("Value = 0", value); 7、通过Remove方法移除指定的键值myDictionary.Remove(1);if(myDictionary.ContainsKey(1).Console.WriteLine("Key:0,Value:1","1", myDictionary1);elseConsole.WriteLine("不存在 Key : 1"

43、;);  4. 其它常见属性和方法的说明:   Comparer:           获取用于确定字典中的键是否相等的 IEqualityComparer。  Count:                  获取包含在 Dictionary中的键/值对的数目。  Item:                    获取或设置与指定的键相关联的值。  Keys:  &

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论