Mic*_*tum 153 .net c# dictionary
我正在使用Dictionary<string, int>
的int
是密钥计数的位置.
现在,我需要访问Dictionary中最后插入的Key,但我不知道它的名字.显而易见的尝试:
int LastCount = mydict[mydict.keys[mydict.keys.Count]];
Run Code Online (Sandbox Code Playgroud)
不起作用,因为Dictionary.Keys
没有实现[] -indexer.
我只是想知道是否有类似的类?我想过使用Stack,但只存储一个字符串.我现在可以创建自己的结构然后使用a Stack<MyStruct>
,但我想知道是否还有另一种选择,本质上是一个在Keys上实现[] -indexer的Dictionary?
小智 215
正如@Falanwe在评论中指出的那样,做这样的事情是不正确的:
int LastCount = mydict.Keys.ElementAt(mydict.Count -1);
Run Code Online (Sandbox Code Playgroud)
您不应该依赖于词典中键的顺序.如果您需要订购,您应该使用OrderedDictionary,如本答案所示.此页面上的其他答案也很有趣.
And*_*ers 57
您可以使用OrderedDictionary.
表示键或索引可访问的键/值对的集合.
小智 17
字典是一个哈希表,所以你不知道插入的顺序!
如果你想知道最后插入的密钥,我建议扩展Dictionary以包含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
}
Run Code Online (Sandbox Code Playgroud)
您将遇到问题,但是当您使用它.Remove()
来克服此问题时,您将必须保留插入的键的有序列表.
为什么不直接扩展字典类以添加最后一个键插入属性.可能会出现以下情况?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
你总是可以这样做:
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
Run Code Online (Sandbox Code Playgroud)
但我不推荐它.无法保证最后插入的密钥位于数组的末尾.MSDN上的密钥的排序未指定,可能会更改.在我非常简短的测试中,它看起来似乎是按照插入的顺序,但你最好建立像堆栈一样的正确簿记 - 正如你的建议(尽管我没有看到基于你的结构的需要)其他语句) - 或单变量缓存,如果您只需要知道最新的密钥.
我认为你可以做这样的事情,语法可能是错的,暂时没有使用C#来获取最后一项
Dictionary<string, int>.KeyCollection keys = mydict.keys;
string lastKey = keys.Last();
Run Code Online (Sandbox Code Playgroud)
或使用Max而不是Last来获取最大值,我不知道哪一个更适合您的代码.
归档时间: |
|
查看次数: |
254317 次 |
最近记录: |