C# - Dictionary with Behaviour of a Ring List?
我需要一本能储存钥匙和物品的戒指目录字典。
.NET框架中有什么可以做到这一点的吗?还是我必须自己写?
我认为你找不到任何内置的东西,但是你可以很容易地使用ordereddictionary实现它。
或使用扩展方法:
编辑:
因为
latest added entry ends up being returned first.
号
所以您可以删除第一项,如:
1 | dictionary.Remove(dictionary.Last().Key); |
&所以您的扩展方法是:
1 2 3 4 5 6 7 | addExtension(this Dictionary<string, object> dictionary, string key, object value) { if(dictionary.Count == 50) dictionary.Remove(dictionary.Last().Key); dictionary.Add(key, value); } |
号
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | class Program { static void Main(string[] args) { var rD = new RingDictionary(50); for (int i = 0; i < 75; i++) { rD.Add(i, i); } foreach (var item in rD.Keys) { Console.WriteLine("{0} {1}", item, rD[item]); } } } class RingDictionary : OrderedDictionary { int indexKey; int _capacity = 0; public int Capacity { get { return _capacity; } set { if (value <= 0) { var errorMessage = typeof(Environment) .GetMethod( "GetResourceString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null) .Invoke(null, new object[] { "ArgumentOutOfRange_NegativeCapacity" }).ToString(); throw new ArgumentException(errorMessage); } _capacity = value; } } public RingDictionary(int capacity) { indexKey = -1; Capacity = capacity; } public new void Add(object key, object value) { indexKey++; if (base.Keys.Count > _capacity) { for (int i = base.Keys.Count-1; i >Capacity-1 ; i--) { base.RemoveAt(i); } } if (base.Keys.Count == _capacity) { base.RemoveAt(indexKey % _capacity); base.Insert(indexKey % _capacity, key, value); } else { base.Add(key, value); } } } |