我看到了这个问题。
如何在 .Net 3.5 中获取 SortedDictionary 中的最后一个元素。
您可以使用 LINQ:
var lastItem = sortedDict.Values.Last();
您还可以获得最后一个密钥:
var lastkey = sortedDict.Keys.Last();
你甚至可以得到最后一个键值对:
var lastKeyValuePair = sortedDict.Last();
这会给你一个KeyValuePair<TKey, TValue>
withKey
和Value
属性。
请注意,如果字典为空,这将引发异常;如果你不想这样,打电话LastOrDefault
。
Last
扩展方法会给你结果,但它必须枚举整个集合才能到达那里。SortedDictionary<K, V>
不公开真是太可惜了Min
,Max
成员特别是在内部考虑到它是由一个SortedSet<KeyValuePair<K, V>>
which hasMin
和Max
properties 支持的。
如果 O(n) 是不可取的,你有几个选择:
切换到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 有什么区别?
编写自己的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)。没有记录,但我检查了代码。
使用精巧的反射来访问作为类的私有成员的支持集,SortedDictionary<K, V>
并调用Min
和Max
属性。可以依靠表达式来编译委托并将其缓存以提高性能。这样做是一个非常糟糕的选择。不敢相信我提出了这个建议。
依赖其他实现,例如。TreeDictionary<K, V>
从 C5开始。他们有FindMin
,两者都是 O(log n)FindMax
您可以使用SortedDictionary.Values.Last();
或者如果你想要键和值
SortedDictionary.Last();
排序列表列表...
list[ Keys[Keys.Count - 1] ]; // returns the last entry in list
正如人们已经指出的那样, Last extension 将枚举整个系列,它对性能的影响可能是致命的。仅从 SortedDict 中删除 10000 个最后的元素,就比对 SortedSet 的类似操作花费了更多的时间。
SortedSet 删除经过的毫秒数:8
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);