2009-10-23 293 views

回答

15

你可以使用LINQ:

var lastItem = sortedDict.Values.Last(); 

您還可以獲得最後的關鍵:

var lastkey = sortedDict.Keys.Last(); 

你甚至可以在最後一個鍵 - 值對:

var lastKeyValuePair = sortedDict.Last(); 

這會給你一個KeyValuePair<TKey, TValue>KeyValue性能。

請注意,如果字典爲空,則會引發異常;如果你不想要,請致電LastOrDefault

+5

這些方法可能觸發枚舉。我想知道是否有任何方法可以在沒有枚舉的情況下獲取最後一個元素(或來自任何位置索引的元素)?由於SortedDictionary被排序爲一棵樹,理論上可能嗎? – 2012-09-25 21:21:56

+1

@RolandPihlakas:理論上,是的。實際上,我不這麼認爲。 – SLaks 2012-09-27 02:35:07

+9

對於來自C++背景的人來說,這很難接受。枚舉整個已排序的字典只是爲了得到最後一個元素,這是無望的低效率。有更強大的C#集合庫嗎? – 2013-02-26 18:16:17

1

您可以使用SortedDictionary.Values.Last();

,或者如果你想要的鍵和值

SortedDictionary.Last(); 
10

Last擴展方法會給你的結果,但它將不得不枚舉整個集合,讓你在那裏。這是一個恥辱SortedDictionary<K, V>不公開MinMax成員特別是考慮到內部它是由SortedSet<KeyValuePair<K, V>>其支持MinMax屬性。

如果O(n)是不可取的,你有幾種選擇:

  1. 切換到SortedList<K, V>。同樣出於某種原因,BCL默認不會打包。您可以使用索引器在O(1)時間內獲取最大值(或最小值)。用擴展方法擴展會很好。

    //Ensure you dont call Min Linq extension method. 
    public KeyValuePair<K, V> Min<K, V>(this SortedList<K, V> dict) 
    { 
        return new KeyValuePair<K, V>(dict.Keys[0], dict.Values[0]); //is O(1) 
    } 
    
    //Ensure you dont call Max Linq extension method. 
    public KeyValuePair<K, V> Max<K, V>(this SortedList<K, V> dict) 
    { 
        var index = dict.Count - 1; //O(1) again 
        return new KeyValuePair<K, V>(dict.Keys[index], dict.Values[index]); 
    } 
    

    SortedList<K, V>附帶其他處罰。所以你可能想看到:What's the difference between SortedList and SortedDictionary?

  2. 寫你自己的SortedDictionary<K, V>類。這是非常微不足道的。有一個SortedSet<KeyValuePair<K, V>>作爲內部容器,並根據Key部分進行比較。例如:

    public class SortedDictionary<K, V> : IDictionary<K, V> 
    { 
        SortedSet<KeyValuePair<K, V>> set; //initialize with appropriate comparer 
    
        public KeyValuePair<K, V> Min { get { return set.Min; } } //O(log n) 
        public KeyValuePair<K, V> Max { get { return set.Max; } } //O(log n) 
    } 
    

    這是O(log n)。沒有記錄,但我檢查了代碼。

  3. 使用fiddly反射訪問後備集,這是SortedDictionary<K, V>類的私有成員,並調用MinMax屬性。可以依賴表達式來編譯委託並緩存它以提高性能。這是一個非常糟糕的選擇。我不敢相信我提出這個建議。

  4. 依靠其他的實現,例如。對於TreeDictionary<K, V> from C5。他們有FindMinFindMaxboth of which are O(log n)

+0

可能想要重新排列這些選項,以便更好的選項位於頂部,而不是讓它們進入,我認爲是您認爲它們的順序。 – Servy 2014-06-11 16:16:50

+0

如何爲第二個選項實現索引器/ TryGetValue? – CodesInChaos 2015-10-18 18:20:47

+0

@CodesInChaos你是對的,這使得它無用。這在.NET中令人傷心,並沒有公開獲取實際參考的方法。我應該編輯答案。 – nawfal 2015-10-18 18:45:50

-1

排序列表列表...

list[ Keys[Keys.Count - 1] ]; // returns the last entry in list 
相關問題