[英]Next key in C# Dictionary
如何使用密鑰將Enumerator
獲取到-Sorted-字典中的項目?
注意: GetEnumerator()
獲取第一個元素的Enumerator
器..
但我需要使用給定鍵為元素獲取一個Enumerator
,以便使用MoveNext()
獲取對下一個元素的訪問權限...
編輯:或者訪問下一個元素的方法......
編輯:我更喜歡const time方法......
謝謝
var enumerator = dictionary.Keys.SkipWhile(k => k != myKey)
myKey是你要找的鑰匙。 如果要對鍵進行排序,可以使用OrderBy擴展方法。
編輯 :您不能使用Dictionary / SortedDictionary在常量中執行此操作。 為什么不實現自己的二叉搜索樹(如SortedDictionary),你將有O(log n)時間查找和O(1)時間.next()
?
也許這對某人有用:
public Dictionary<string, int> myDictionary = new Dictionary<string, int>();
public string myCurrentKey = "some key 5";
for (int i = 1; i <= 10; i++) {
myDictionary.Add(string.Format("some key {0}", i), i);
}
private void MoveIndex(int dir) { // param "dir" can be 1 or -1 to move index forward or backward
List<string> keys = new List<string>(myDictionary.Keys);
int newIndex = keys.IndexOf(myCurrentKey) - dir;
if (newIndex < 0) {
newIndex = myDictionary.Count - 1;
} else if (newIndex > myDictionary.Count - 1) {
newIndex = 0;
}
myCurrentKey = keys[newIndex];
}
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 5
MoveIndex(1);
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 6
MoveIndex(-1);
MoveIndex(-1);
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 4
你不能用Dictionary做到這一點。 您可以通過索引實現具有訪問權限的可能性,因此您可以使用SortedList而不是Dictionary。 你也可以看看SkipWhile 。
雖然你可以有這樣的解決方法:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> pair in dictionary)
{
// you can check the key you need and assume that the next one will be what you need.
}
但當然這不是最好的主意。
如果您安裝了Framework> = 3.5,請使用SkipWhile Janus Tondering和LukeH建議。 對於較低的框架版本,您必須自己完成(fe填充第二個字典,其中keyvaluepairs從您的密鑰到最后)。
var query = yourDictionary.SkipWhile(kvp => kvp.Key != keyToFind);
foreach (var result in query)
{
// ...
}
最簡單的選擇是使用SortedList
,然后向其添加一個擴展方法,返回一個IEnumerable
其元素大於或等於給定的鍵。 下面的GetElementsGreaterThanOrEqual
方法的復雜性是O(log(n))來獲取第一個元素,然后每次迭代后都是O(1)。
public static class SortedListExtension
{
public static IEnumerable<KeyValuePair<TKey, TValue>> GetElementsGreaterThanOrEqual<TKey, TValue>(this SortedList<TKey, TValue> instance, TKey target) where TKey : IComparable<TKey>
{
int index = instance.BinarySearch(target);
if (index < 0)
{
index = ~index;
}
for (int i = index; i < instance.Count; i++)
{
yield return new KeyValuePair<TKey, TValue>(instance.Keys[i], instance.Values[i]);
}
}
public static int BinarySearch<TKey, TValue>(this SortedList<TKey, TValue> instance, TKey target) where TKey : IComparable<TKey>
{
int lo = 0;
int hi = instance.Count - 1;
while (lo <= hi)
{
int index = lo + ((hi - lo) >> 1);
int compare = instance.Keys[index].CompareTo(target);
if (compare == 0)
{
return index;
}
else
{
if (compare < 0)
{
lo = index + 1;
}
else
{
hi = index - 1;
}
}
}
return ~lo;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.