summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
blob: 3fe7716203012f6abe501c2fc5e3ec9aa1ac164c (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// 

namespace System.Collections.ObjectModel
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
       
    [Serializable]
    [DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))]
    [DebuggerDisplay("Count = {Count}")]        
    public abstract class KeyedCollection<TKey,TItem>: Collection<TItem>
    {
        const int defaultThreshold = 0;

        IEqualityComparer<TKey> comparer;
        Dictionary<TKey,TItem> dict;
        int keyCount;
        int threshold;

        protected KeyedCollection(): this(null, defaultThreshold) {}

        protected KeyedCollection(IEqualityComparer<TKey> comparer): this(comparer, defaultThreshold) {}


        protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
            : base(new List<TItem>()) { // Be explicit about the use of List<T> so we can foreach over
                                        // Items internally without enumerator allocations.
            if (comparer == null) { 
                comparer = EqualityComparer<TKey>.Default;
            }

            if (dictionaryCreationThreshold == -1) {
                dictionaryCreationThreshold = int.MaxValue;
            }

            if( dictionaryCreationThreshold < -1) {
                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold);
            }

            this.comparer = comparer;
            this.threshold = dictionaryCreationThreshold;
        }

        /// <summary>
        /// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator.
        /// </summary>
        new private List<TItem> Items {
            get {
                Debug.Assert(base.Items is List<TItem>);

                return (List<TItem>)base.Items;
            }
        }

        public IEqualityComparer<TKey> Comparer {
            get {
                return comparer;                
            }               
        }

        public TItem this[TKey key] {
            get {
                if( key == null) {
                    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
                }

                if (dict != null) {
                    return dict[key];
                }

                foreach (TItem item in Items) {
                    if (comparer.Equals(GetKeyForItem(item), key)) return item;
                }

                ThrowHelper.ThrowKeyNotFoundException();
                return default(TItem);
            }
        }

        public bool Contains(TKey key) {
            if( key == null) {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }
            
            if (dict != null) {
                return dict.ContainsKey(key);
            }

            foreach (TItem item in Items) {
                if (comparer.Equals(GetKeyForItem(item), key)) return true;
            }
            return false;
        }

        private bool ContainsItem(TItem item) {                        
            TKey key;
            if( (dict == null) || ((key = GetKeyForItem(item)) == null)) {
                return Items.Contains(item);
            }

            TItem itemInDict;
            bool exist = dict.TryGetValue(key, out itemInDict);
            if( exist) {
                return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
            }
            return false;
        }

        public bool Remove(TKey key) {
            if( key == null) {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }
            
            if (dict != null) {
                if (dict.ContainsKey(key)) {
                    return Remove(dict[key]);
                }

                return false;
            }

            for (int i = 0; i < Items.Count; i++) {
                if (comparer.Equals(GetKeyForItem(Items[i]), key)) {
                    RemoveItem(i);
                    return true;
                }
            }
            return false;
        }

        protected IDictionary<TKey,TItem> Dictionary {
            get { return dict; }
        }

        protected void ChangeItemKey(TItem item, TKey newKey) {
            // check if the item exists in the collection
            if( !ContainsItem(item)) {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist);
            }

            TKey oldKey = GetKeyForItem(item);            
            if (!comparer.Equals(oldKey, newKey)) {
                if (newKey != null) {
                    AddKey(newKey, item);
                }

                if (oldKey != null) {
                    RemoveKey(oldKey);
                }
            }
        }

        protected override void ClearItems() {
            base.ClearItems();
            if (dict != null) {
                dict.Clear();
            }

            keyCount = 0;
        }

        protected abstract TKey GetKeyForItem(TItem item);

        protected override void InsertItem(int index, TItem item) {
            TKey key = GetKeyForItem(item);
            if (key != null) {
                AddKey(key, item);
            }
            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index) {
            TKey key = GetKeyForItem(Items[index]);
            if (key != null) {
                RemoveKey(key);
            }
            base.RemoveItem(index);
        }

        protected override void SetItem(int index, TItem item) {
            TKey newKey = GetKeyForItem(item);
            TKey oldKey = GetKeyForItem(Items[index]);

            if (comparer.Equals(oldKey, newKey)) {
                if (newKey != null && dict != null) {
                    dict[newKey] = item;
                }
            }
            else {
                if (newKey != null) {
                    AddKey(newKey, item);
                }

                if (oldKey != null) {
                    RemoveKey(oldKey);
                }
            }
            base.SetItem(index, item);
        }

        private void AddKey(TKey key, TItem item) {
            if (dict != null) {
                dict.Add(key, item);
            }
            else if (keyCount == threshold) {
                CreateDictionary();
                dict.Add(key, item);
            }
            else {
                if (Contains(key)) {
                    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
                }

                keyCount++;
            }
        }

        private void CreateDictionary() {
            dict = new Dictionary<TKey,TItem>(comparer);
            foreach (TItem item in Items) {
                TKey key = GetKeyForItem(item);
                if (key != null) {
                    dict.Add(key, item);
                }
            }
        }

        private void RemoveKey(TKey key) {
            Debug.Assert(key != null, "key shouldn't be null!");
            if (dict != null) {
                dict.Remove(key);
            }
            else {
                keyCount--;
            }
        }
    }
}