C# 字典常用方法

/*
               #########                       
              ############                     
              #############                    
             ##  ###########                   
            ###  ###### #####                  
            ### #######   ####                 
           ###  ########## ####                
          ####  ########### ####               
         ####   ###########  #####             
        #####   ### ########   #####           
       #####   ###   ########   ######         
      ######   ###  ###########   ######       
     ######   #### ##############  ######      
    #######  #####################  ######     
    #######  ######################  ######    
   #######  ###### #################  ######   
   #######  ###### ###### #########   ######   
   #######    ##  ######   ######     ######   
   #######        ######    #####     #####    
    ######        #####     #####     ####     
     #####        ####      #####     ###      
      #####       ###        ###      #        
        ###       ###        ###              
         ##       ###        ###               
__________#_______####_______####______________

    身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。
                我们的未来没有BUG              
* ==============================================================================
* Filename: Dictionary
* Created:  2017/5/2 
* Author:   ShangHai WangYuChen
* ==============================================================================
*/
using UnityEngine;
using System.Collections.Generic;
using System.Linq;


public class Dictionary : MonoBehaviour {
    Dictionary<int, string> list = new Dictionary<int, string>();
	void Start () {
        //添加元素
        list.Add(1, "1111");
        list.Add(2, "2222");
        list.Add(3, "3333");
        list.Add(4, "4444");
        list.Add(5, "5555");
        //更改值
        list[1] = "qqqq";

        // 情形一:不存在才添加
        if (list.ContainsKey(6)==false)
        {
            list.Add(6, "6666");
        }
        // 情形二:不存在添加,存在则替换
        if (list.ContainsKey(2) == false)
        {
            list.Add(2, "wwww");
        }
        else {
            list[2] = "wwww";
        }
        Debug.Log("获得字典的数目: " + list.Count);
        Debug.Log("获得键的数目: "+list.Keys.Count);
        Debug.Log("获得值的数目: " + list.Values.Count);
        //移除所指定的键的值
        list.Remove(3);

        foreach (var item in list)
        {
            Debug.Log("Key的值: " + item.Key + "   value的值: " + item.Value);
            //通过值找键
            if (list.ContainsValue("6666"))
            {
                Debug.Log(item.Key);
            }
            //通过键找值
            if (list.ContainsKey(2))
            {
                Debug.Log(item.Value);
            }
        }
    }
}

  

posted @ 2017-05-02 14:35  一只默默奮鬥的程序菌  阅读(435)  评论(0编辑  收藏  举报