程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# Dictionary用法

C# Dictionary用法

編輯:C#入門知識

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<int, string> dict = new Dictionary<int, string>();
        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<string, string[]> dict = new Dictionary<string, string[]>();
        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 { get; set; }
    public string UserName { get; set; }

}


摘自  Mr.Shaw

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved