C#,Dictionary,asp.net 字典

來源:互聯網
上載者:User

簡介
在C#中,Dictionary提供快速的基於兼職的元素尋找。當你有很多元素的時候可以使用它。它包含在System.Collections.Generic名空間中。

在使用前,你必須聲明它的鍵類型和實值型別。

詳細說明
必須包含名空間System.Collection.Generic
Dictionary裡面的每一個元素都是一個索引值對(由二個元素組成:鍵和值)
鍵必須是唯一的,而值不需要唯一的
鍵和值都可以是任何類型(比如:string, int, 自訂類型,等等)
通過一個鍵讀取一個值的時間是接近O(1)
索引值對之間的偏序可以不定義
建立和初始化一個Dictionary對象
Dictionary myDictionary = new Dictionary();
添加鍵
static void Main(string[] args)
{
  Dictionary d = new Dictionary();
  d.Add("C#", 2);
  d.Add("C", 0);
  d.Add("C++", -1);
}
尋找鍵
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add("C#", 2);
   d.Add("VB", 1);
   d.Add("C", 0);
   d.Add("C++", -1);
   if (d.ContainsKey("VB")) // True
   {
      int p = d["VB"];
      Console.WriteLine(p);
     } 
 
     if (d.ContainsKey("C"))
     {
       int p1 = d["C"];
       Console.WriteLine(p1);
     }
 }
刪除元素
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add("C#", 2);
   d.Add("VB", 1);
   d.Add("C", 0);
   d.Add("C++", -1);
 
   d.Remove("C");    
   d.Remove("VB");
 }
使用ContainsValue尋找值的存在
static void Main(string[] args)
{
    Dictionary d = new Dictionary();
    d.Add("C#", 2);
    d.Add("VB", 1);
    d.Add("C", 0);
    d.Add("C++", -1);
    if (d.ContainsValue(1))
    {
        Console.WriteLine("VB");
    }
    if (d.ContainsValue(2))
    {
       Console.WriteLine("C#");
    }
    if (d.ContainsValue(0))
    {
       Console.WriteLine("C");
    }
    if (d.ContainsValue(-1))
      {
          Console.WriteLine("C++");
      }               
}
KeyNotFoundException
如果你嘗試讀取字典中一個不存在的鍵,那麼你會得到一個KeyNotFoundException。所有在讀取一個鍵之前,你必須先使用ContainKey來核對鍵是否存在字典中。

基於int鍵的Dictionary
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add(1000, "Planet");
   d.Add(2000, "Stars");
   // lookup the int in the dictionary.
   if (d.ContainsKey(1000))
   {
        Console.WriteLine(true);
   }
      Console.ReadLine();
}
排序字典SortedDictionary
在排序字典中,當添加元素時字典必須進行排序,所以插入的速度會比較慢點。但是因為元素是有序儲存的,所以元素的尋找可以使用二分搜尋等一些效率更高的搜尋。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.