如何檢查字典是否包含從預定義鍵開始的值?例如,我想搜索字典後後的某個特定鍵,而不是從第一個開始搜索。Dictionary.Contains at specific start index
我該如何做到這一點?
如何檢查字典是否包含從預定義鍵開始的值?例如,我想搜索字典後後的某個特定鍵,而不是從第一個開始搜索。Dictionary.Contains at specific start index
我該如何做到這一點?
不確定在這種情況下字典是最適合您使用的,因爲(如前所述)訂單無法得到保證。但是,如果您使用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);
在這個例子中示出所得到的信息將是使用Skip
和Take
方法「B 2」。它「跳過」第一個「1」和「取得」下一個「1」;
編輯(重構使用KeyValuePair列表,而不是字符串)。
也許你需要的是一個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);
}
}
}
如果它是一個普通的Dictionary<TKey, TValue>
那麼你不能,除非你第一次排序。
你可以做的是使用SortedList<TKey, TValue>
或SortedDictionary<TKey, TValue>
,這兩種都按鍵排序。
你是否假設密鑰按照它們添加的順序存儲?你如何定義「在一個鍵之後」? – itsme86
除了按鍵查找以外,還可以使用字典,聽起來就像詞典濫用,並要求另一種類型的收集。但正如@ itsme86所說:請詳細闡述一下你的意思。 –
[MSDN](http://msdn.microsoft.com/zh-cn/library/xfhwa508.aspx)陳述'Dictionary':「項目返回的順序未定義。雖然這指的是IEnumerable >實現,但該語句通常對字典中元素的順序有效。它是**未定義**。因此,**之後的** first **或**之類的術語對於字典中的鍵是沒有意義的。 –