这在使用
Dictionary<TKey, TValue>
时是不可能的,因为当枚举时它以无序的方式呈现其值。虽然有
SortedDictionary<TKey, TValue>
提供排序,但它是通过直接使用
IComparer<TKey>
来针对键值进行排序的。在这里,您需要将键设置为一个
String
,并基于
int
进行排序。这两种类型都无法实现。
我认为您需要实现一个新类型,具有这些非常特定的语义。例如。
class OrderedMap<TKey, TValue> {
private readonly Dictionary<TKey, TValue> _map = new Dictionary<TKey, TValue>();
private readonly List<TKey> _list = new List<TKey>();
public void Add(TKey key, TValue value) {
if (!_map.ContainsKey(key)) {
_list.Add(key);
}
_map[key] = value;
}
public void Add(TKey key, TValue value, int index) {
if (_map.ContainsKey(key)) {
_list.Remove(key);
}
_map[key] = value;
_list.Insert(index, key);
}
public TValue GetValue(TKey key) {
return _map[key];
}
public IEnumerabe<KeyValuePair<TKey, TValue>> GetItems() {
foreach (var key in _list) {
var value = _map[key];
yield return new KeyValuePair<TKey, TValue>(key, value);
}
}
}
请注意,与传统的Dictionary<TKey, TValue>
相比,这会带来一些非常显著的性能差异。例如Add
和Remove
的速度较慢。