14

我看到了这个问题

如何在 .Net 3.5 中获取 SortedDictionary 中的最后一个元素。

4

5 回答 5

20

您可以使用 LINQ:

var lastItem = sortedDict.Values.Last();

您还可以获得最后一个密钥:

var lastkey = sortedDict.Keys.Last();

你甚至可以得到最后一个键值对:

var lastKeyValuePair = sortedDict.Last();

这会给你一个KeyValuePair<TKey, TValue>withKeyValue属性。

请注意,如果字典为空,这将引发异常;如果你不想这样,打电话LastOrDefault

于 2009-10-23T12:09:03.610 回答
20

Last扩展方法会给你结果,但它必须枚举整个集合才能到达那里。SortedDictionary<K, V>不公开真是太可惜了MinMax成员特别是在内部考虑到它是由一个SortedSet<KeyValuePair<K, V>>which hasMinMaxproperties 支持的。

如果 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>附带其他处罚。所以你可能想看看:SortedList 和 SortedDictionary 有什么区别?

  2. 编写自己的SortedDictionary<K, V>类。这是非常微不足道的。将 aSortedSet<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. 使用精巧的反射来访问作为类的私有成员的支持集,SortedDictionary<K, V>并调用MinMax属性。可以依靠表达式来编译委托并将其缓存以提高性能。这样做是一个非常糟糕的选择。不敢相信我提出了这个建议。

  4. 依赖其他实现,例如。TreeDictionary<K, V>从 C5开始。他们有FindMin两者都是 O(log n)FindMax

于 2014-06-11T16:12:58.390 回答
2

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

或者如果你想要键和值

SortedDictionary.Last();
于 2009-10-23T12:09:01.770 回答
0

排序列表列表...

list[ Keys[Keys.Count - 1] ];  // returns the last entry in list
于 2016-02-03T14:16:17.120 回答
0

正如人们已经指出的那样, Last extension 将枚举整个系列,它对性能的影响可能是致命的。仅从 SortedDict 中删除 10000 个最后的元素,就比对 SortedSet 的类似操作花费了更多的时间。

  1. SortedSet 删除经过的毫秒数:8

  2. SortedDict 删除已用毫秒:3697

    // 在下面的代码中,ss 是 SortedSet,sd 是 SortedDictionary,它们都包含相同的 10000 个元素。

     sw.Start();
     while (ss.Count != 0)
     {
         ss.Remove(ss.Max);
     }
    
     sw.Stop();
     Console.WriteLine("SortedSet Removal Elapsed ms : {0}", sw.ElapsedMilliseconds);
    
     sw.Reset();
    
     sw.Start();
     while (sd.Count != 0)
     {
         sd.Remove(sd.Keys.Last());
     }
    
     sw.Stop();
     Console.WriteLine("Dict Removal Elapsed ms : {0}", sw.ElapsedMilliseconds);
    
于 2020-09-19T17:19:21.297 回答