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>与Key和Value性质.
请注意,如果字典为空,这将抛出异常; 如果你不想那样,请致电LastOrDefault.
naw*_*fal 12
Lastextension方法会给你结果,但它必须枚举整个集合才能到达那里.这是一种耻辱SortedDictionary<K, V>不暴露Min和Max成员特别考虑内部它由一个SortedSet<KeyValuePair<K, V>>具有Min和Max属性的支持.
如果不希望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]);
}
Run Code Online (Sandbox Code Playgroud)
SortedList<K, V>还有其他处罚.所以你可能想看看:SortedList和SortedDictionary有什么区别?
写自己的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).没有记录,但我检查了代码.
使用fiddly反射来访问后台集,后台集是SortedDictionary<K, V>类的私有成员,并调用Min和Max属性.可以依赖表达式来编译委托并将其缓存以提高性能.这样做是一个非常糟糕的选择.不敢相信我建议这个.
依赖于其他实现,例如.对于TreeDictionary<K, V>从C5.他们有FindMin和这两者都是O(log n)的FindMax