c# dictionary 学习

 
//Dictionary的Value为一个数组
public static void DicSample2() { Dictionary<String, String[]> dic = new Dictionary<String, String[]>(); String[] ZheJiang = { "Huzhou", "HangZhou", "TaiZhou" }; String[] ShangHai = { "Budong", "Buxi" }; dic.Add("ZJ", ZheJiang); dic.Add("SH", ShangHai); Console.WriteLine("Output :" + dic["ZJ"][0]); }
//Dictionary的Value为一个类
public static void DicSample3()
 {
     Dictionary<String, Student> stuList = new Dictionary<String, Student>();
     Student stu = null;
     for (int i = 0; i < 3; i++ )
     {
         stu = new Student();
         stu.Name = i.ToString();
         stu.Name = "StuName" + i.ToString();
         stuList.Add(i.ToString(), stu);
     }
 
     foreach (var student in stuList)
     {
         Console.WriteLine("Output : Key {0}, Num : {1}, Name {2}", student.Key, student.Value.Name, student.Value.Name);
     }
 }

//Student类:

public class Student
{
    public String Num { get; set; }
    public String Name { get; set; }
}
//Dictionary的扩展方法使用

 

/// <summary>
/// Dictionary的扩展方法使用
/// </summary>
 public static void DicSample4()
 {
     //1)普通调用
     Dictionary<int, String> dict = new Dictionary<int, String>();
     DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan");
     DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu");
     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu");
     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu");
     DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi");
 
     //2)TryAdd 和 AddOrReplace 这两个方法具有较强自我描述能力,用起来很省心,而且也简单:
     dict.AddOrPeplace(20, "Orange");
     dict.TryAdd(21, "Banana");
     dict.TryAdd(22, "apple");
 
     //3)像Linq或jQuery一样连起来写   
     dict.TryAdd(10, "Bob")
         .TryAdd(11, "Tom")
         .AddOrPeplace(12, "Jom");
 
     //4) 获取值
     String F = "Ba";
     dict.TryGetValue(31, out F);
     Console.WriteLine("F : {0}",F);
 
     foreach (var dic in dict)
     {
         Console.WriteLine("Output : Key : {0}, Value : {1}", dic.Key, dic.Value);
     }
     //5)下面是使用GetValue获取值
     var v1 = dict.GetValue(111,null);
     var v2 = dict.GetValue(10,"abc");
 
     //6)批量添加
     var dict1 = new Dictionary<int,int>();
     dict1.AddOrPeplace(3, 3);
     dict1.AddOrPeplace(5, 5);
 
     var dict2 = new Dictionary<int, int>();
     dict2.AddOrPeplace(1, 1);
     dict2.AddOrPeplace(4, 4);
     dict2.AddRange(dict1, false);
 }
  扩展方法所在的类

public static class DictionaryExtensionMethodClass 
{
    /// <summary>
    /// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常
    /// </summary>
    public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        if (dict.ContainsKey(key) == false)
            dict.Add(key, value);
        return dict;
    }
 
    /// <summary>
    /// 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换
    /// </summary>
    public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        dict[key] = value;
        return dict;
    }
 
    /// <summary>
    /// 获取与指定的键相关联的值,如果没有则返回输入的默认值
    /// </summary>
    public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
    {
        return dict.ContainsKey(key)?dict[key] : defaultValue;
    }
 
    /// <summary>
    /// 向字典中批量添加键值对
    /// </summary>
    /// <param name="replaceExisted">如果已存在,是否替换</param>
    public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
    {
        foreach (var item in values)
        {
            if (dict.ContainsKey(item.Key) == false || replaceExisted)
                dict[item.Key] = item.Value;
        }
        return dict;
    }
 
 
}
//定义
    Dictionary<string, string> openWith = new Dictionary<string, string>();
 

    //添加元素
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");
 

    //取值
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 

    //更改值
    openWith["rtf"] = "winword.exe";
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 

    //遍历key
    foreach (string key in openWith.Keys)
    {
        Console.WriteLine("Key = {0}", key);
    }
 

复制代码
    //遍历value
    foreach (string value in openWith.Values)
    {
        Console.WriteLine("value = {0}", value);
    }

    //遍历value, Second Method
    Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
    foreach (string s in valueColl)
    {
        Console.WriteLine("Second Method, Value = {0}", s);
    }
复制代码
 

    //遍历字典
    foreach (KeyValuePair<string, string> kvp in openWith)
    {
        Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    }
 

复制代码
    //添加存在的元素
    try
    {
        openWith.Add("txt", "winword.exe");
    }
    catch (ArgumentException)
    {
        Console.WriteLine("An element with Key = \"txt\" already exists.");
    }
复制代码
 

    //删除元素
    openWith.Remove("doc");
    if (!openWith.ContainsKey("doc"))
    {
        Console.WriteLine("Key \"doc\" is not found.");
    }
 

    //判断键存在
    if (openWith.ContainsKey("bmp")) // True 
    {
        Console.WriteLine("An element with Key = \"bmp\" exists.");
    }

 

//可以添加任何类型
Dictionary<int,List<string>> DicObj = new Dictionary<int,List<string>>();

 

posted @ 2014-06-20 00:24  改变你我  阅读(331)  评论(0编辑  收藏  举报