1+ using System . Collections ;
2+ using System . Collections . Generic ;
3+
4+ namespace ThermoRawFileParser . Util
5+ {
6+ //https://social.msdn.microsoft.com/Forums/vstudio/en-US/789c37ea-b9bf-4512-a418-f4f9532c59bf/dictionary-with-limited-size?forum=csharpgeneral
7+ public class LimitedSizeDictionary < TKey , TValue > : IDictionary < TKey , TValue >
8+ {
9+ private readonly Dictionary < TKey , TValue > _dict ;
10+ private Queue < TKey > _queue ;
11+ private readonly int _size ;
12+
13+ public LimitedSizeDictionary ( int size )
14+ {
15+ _size = size ;
16+ _dict = new Dictionary < TKey , TValue > ( size + 1 ) ;
17+ _queue = new Queue < TKey > ( size ) ;
18+ }
19+
20+ public void Add ( TKey key , TValue value )
21+ {
22+ _dict . Add ( key , value ) ;
23+ if ( _queue . Count == _size )
24+ _dict . Remove ( _queue . Dequeue ( ) ) ;
25+ _queue . Enqueue ( key ) ;
26+ }
27+
28+ public bool ContainsKey ( TKey key )
29+ {
30+ return _dict . ContainsKey ( key ) ;
31+ }
32+
33+ public bool Remove ( TKey key )
34+ {
35+ if ( _dict . Remove ( key ) )
36+ {
37+ var newQueue = new Queue < TKey > ( _size ) ;
38+ foreach ( var item in _queue )
39+ if ( ! _dict . Comparer . Equals ( item , key ) )
40+ newQueue . Enqueue ( item ) ;
41+ _queue = newQueue ;
42+ return true ;
43+ }
44+ else
45+ return false ;
46+ }
47+
48+ public bool TryGetValue ( TKey key , out TValue value )
49+ {
50+ return _dict . TryGetValue ( key , out value ) ;
51+ }
52+
53+ public TValue this [ TKey key ]
54+ {
55+ get => _dict [ key ] ;
56+ set => _dict [ key ] = value ;
57+ }
58+
59+ public ICollection < TKey > Keys => _dict . Keys ;
60+
61+ public ICollection < TValue > Values => _dict . Values ;
62+
63+ public IEnumerator < KeyValuePair < TKey , TValue > > GetEnumerator ( )
64+ {
65+ return _dict . GetEnumerator ( ) ;
66+ }
67+
68+ IEnumerator IEnumerable . GetEnumerator ( )
69+ {
70+ return ( ( IEnumerable ) _dict ) . GetEnumerator ( ) ;
71+ }
72+
73+ public void Add ( KeyValuePair < TKey , TValue > item )
74+ {
75+ ( ( IDictionary < TKey , TValue > ) _dict ) . Add ( item ) ;
76+ }
77+
78+ public void Clear ( )
79+ {
80+ _dict . Clear ( ) ;
81+ }
82+
83+ public bool Contains ( KeyValuePair < TKey , TValue > item )
84+ {
85+ return ( ( IDictionary < TKey , TValue > ) _dict ) . Contains ( item ) ;
86+ }
87+
88+ public void CopyTo ( KeyValuePair < TKey , TValue > [ ] array , int arrayIndex )
89+ {
90+ ( ( IDictionary < TKey , TValue > ) _dict ) . CopyTo ( array , arrayIndex ) ;
91+ }
92+
93+ public bool Remove ( KeyValuePair < TKey , TValue > item )
94+ {
95+ return ( ( IDictionary < TKey , TValue > ) _dict ) . Remove ( item ) ;
96+ }
97+
98+ public int Count => _dict . Count ;
99+
100+ public bool IsReadOnly => ( ( IDictionary < TKey , TValue > ) _dict ) . IsReadOnly ;
101+ }
102+ }
0 commit comments