我使用的是一个Dictionary<string, int>
,其中int
是密钥的计数。
现在,我需要访问字典中最后插入的键,但我不知道它的名称。显而易见的尝试是:
int LastCount = mydict[mydict.keys[mydict.keys.Count]];
不起作用,因为Dictionary.Keys
不实现[]-indexer。
我想知道有没有类似的课程?我考虑过使用Stack,但它只存储一个字符串。我现在可以创建自己的结构,然后使用Stack<MyStruct>
,但我想知道是否还有另一种选择,本质上是在键上实现[]-indexer的字典?
发布于 2009-04-16 14:09:30
字典是一个哈希表,所以你不知道插入的顺序!
如果您想知道最后插入的键,我建议扩展字典,使其包含一个LastKeyInserted值。
例如:
public MyDictionary<K, T> : IDictionary<K, T>
{
private IDictionary<K, T> _InnerDictionary;
public K LastInsertedKey { get; set; }
public MyDictionary()
{
_InnerDictionary = new Dictionary<K, T>();
}
#region Implementation of IDictionary
public void Add(KeyValuePair<K, T> item)
{
_InnerDictionary.Add(item);
LastInsertedKey = item.Key;
}
public void Add(K key, T value)
{
_InnerDictionary.Add(key, value);
LastInsertedKey = key;
}
.... rest of IDictionary methods
#endregion
}
但是,当您使用.Remove()
时会遇到问题,因此要克服这个问题,您必须保持所插入的键的有序列表。
发布于 2008-08-07 11:15:35
为什么不简单地扩展字典类,添加最后一个键插入的属性。可能是下面这样的内容?
public class ExtendedDictionary : Dictionary<string, int>
{
private int lastKeyInserted = -1;
public int LastKeyInserted
{
get { return lastKeyInserted; }
set { lastKeyInserted = value; }
}
public void AddNew(string s, int i)
{
lastKeyInserted = i;
base.Add(s, i);
}
}
发布于 2008-08-07 01:13:22
你可以这样做:
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
但我不建议你这么做。不能保证最后插入的键会在数组的末尾。密钥on MSDN的排序未指定,可能会更改。在我非常简短的测试中,它似乎是按插入顺序排列的,但如果只需要知道最新的键,最好像您建议的那样在适当的记账中构建堆栈(尽管我不认为需要基于其他语句的结构)或单变量缓存。
https://stackoverflow.com/questions/4227
复制相似问题