2012-12-19 78 views
-1

如何檢查字典是否包含從預定義鍵開始的值?例如,我想搜索字典後的某個特定鍵,而不是從第一個開始搜索。Dictionary.Contains at specific start index

我該如何做到這一點?

+7

你是否假設密鑰按照它們添加的順序存儲?你如何定義「在一個鍵之後」? – itsme86

+3

除了按鍵查找以外,還可以使用字典,聽起來就像詞典濫用,並要求另一種類型的收集。但正如@ itsme86所說:請詳細闡述一下你的意思。 –

+0

[MSDN](http://msdn.microsoft.com/zh-cn/library/xfhwa508.aspx)陳述'Dictionary ':「項目返回的順序未定義。雖然這指的是IEnumerable >實現,但該語句通常對字典中元素的順序有效。它是**未定義**。因此,**之後的** first **或**之類的術語對於字典中的鍵是沒有意義的。 –

回答

1

不確定在這種情況下字典是最適合您使用的,因爲(如前所述)訂單無法得到保證。但是,如果您使用List<>,則可以獲得您正在查找的行爲。如下例所示:

 var items = new List<KeyValuePair<string, string>>(); 
     items.Add(new KeyValuePair<string, string>("A", "1")); 
     items.Add(new KeyValuePair<string, string>("B", "2")); 
     items.Add(new KeyValuePair<string, string>("C", "3")); 
     var results = items.Skip(1).Take(1).ToList(); 

     MessageBox.Show(results[0].Key + " " + results[0].Value); 

在這個例子中示出所得到的信息將是使用SkipTake方法「B 2」。它「跳過」第一個「1」和「取得」下一個「1」;

編輯(重構使用KeyValuePair列表,而不是字符串)。

+2

我不明白這對OP有何用處,因爲我懷疑如果他不需要內在的鍵/值選擇,他會使用字典。您可能會建議他用您的方法嘗試使用List >。 –

+0

@maciej謝謝。我做了編輯。 – jmrnet

+0

@JesseCarter很好的建議。我試圖簡單地展示Skip and Take功能,但您的建議可能更有用。謝謝。 – jmrnet

2

也許你需要的是一個OrderedDictionary,它提供了插入順序控制。這裏有一個例子,也包含一些搜索速度統計。

using System; 
using System.Collections; 
using System.Collections.Specialized; 
using System.Diagnostics; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      var startIndex = 1000000; // 00:00:00.0004876 
      //var startIndex = 1;  // 00:00:00.0152319 

      var searchedKey = "1"; 

      OrderedDictionary orderedDictionary = new OrderedDictionary(); 

      //populate 
      for (int i = 2; i < 1000002; i++) 
      { 
       orderedDictionary.Add(i.ToString(), "X"); 
      } 
      orderedDictionary.Add("1", "A"); 

      //copy the keys 
      String[] keys = new String[1000006]; 
      orderedDictionary.Keys.CopyTo(keys, 0); 

      //measure the time with a System.Diagnostics.StopWatch 
      Stopwatch watch = new Stopwatch(); 
      watch.Start(); 

      for (int i = startIndex; i < orderedDictionary.Count; i++) 
      { 
       if (keys[i] == searchedKey) 
       { 
        Console.WriteLine(orderedDictionary[i]); 
        break; 
       } 
      } 
      watch.Stop(); 

      Console.WriteLine(watch.Elapsed); 
     } 
    } 
} 
相關問題