获取SortedDictionary中的最后一个元素

leo*_*ora 10 c# collections sorteddictionary

我看到了这个问题.

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

SLa*_*aks 17

您可以使用LINQ:

var lastItem = sortedDict.Values.Last();
Run Code Online (Sandbox Code Playgroud)

你也可以得到最后一把钥匙:

var lastkey = sortedDict.Keys.Last();
Run Code Online (Sandbox Code Playgroud)

您甚至可以获得最后一个键值对:

var lastKeyValuePair = sortedDict.Last();
Run Code Online (Sandbox Code Playgroud)

这会给你一个KeyValuePair<TKey, TValue>KeyValue性质.

请注意,如果字典为空,这将抛出异常; 如果你不想那样,请致电LastOrDefault.

  • 对于来自C++背景的人来说,这很难接受.枚举整个排序字典只是为了得到最后一个元素是无望的低效率.是否有更强大的C#Collection库? (11认同)
  • 这些方法可能会触发枚举.我想知道是否有任何方法可以在没有枚举的情况下获取最后一个元素(或来自任何位置索引的元素)?由于SortedDictionary被分类到树中,它在理论上可能是可能的吗? (5认同)
  • @ThunderGr:不;它没有索引器。 (2认同)
  • @Lander:一旦删除元素,这将完全中断。 (2认同)

naw*_*fal 12

Lastextension方法会给你结果,但它必须枚举整个集合才能到达那里.这是一种耻辱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]);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    SortedList<K, V>还有其他处罚.所以你可能想看看:SortedList和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)
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这是O(log n).没有记录,但我检查了代码.

  3. 使用fiddly反射来访问后台集,后台集是SortedDictionary<K, V>类的私有成员,并调用MinMax属性.可以依赖表达式来编译委托并将其缓存以提高性能.这样做是一个非常糟糕的选择.不敢相信我建议这个.

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