| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ObservableKeyedCollection.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Linq; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Collections; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// A keyed observable collection that maintains an internal dictionary for fast O(1) key lookups. |
| | | 15 | | /// Optimized for performance with automatic dictionary creation and capacity management. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <typeparam name="TKey">The type of the key for items in the collection.</typeparam> |
| | | 18 | | /// <typeparam name="T">The type of the items in the collection.</typeparam> |
| | | 19 | | public abstract class ObservableKeyedCollection<TKey, T> : ObservableRangeCollection<T> |
| | | 20 | | where TKey : notnull |
| | | 21 | | { |
| | | 22 | | private readonly int _dictionaryCreationThreshold; |
| | | 23 | | private Dictionary<TKey, T>? _dict; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Initializes a new instance of the <see cref="ObservableKeyedCollection{TKey, T}"/> class. |
| | | 27 | | /// </summary> |
| | | 28 | | protected ObservableKeyedCollection() |
| | 6 | 29 | | : this([]) |
| | | 30 | | { |
| | 6 | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Initializes a new instance of the <see cref="ObservableKeyedCollection{TKey, T}"/> class with the specified comp |
| | | 35 | | /// </summary> |
| | | 36 | | /// <param name="comparer">The equality comparer used to compare keys.</param> |
| | | 37 | | /// <param name="dictionaryCreationThreshold">Minimum items before creating dictionary. 0 = always create.</param> |
| | | 38 | | protected ObservableKeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold = 0) |
| | 66 | 39 | | : this([], comparer, dictionaryCreationThreshold) |
| | | 40 | | { |
| | 66 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Initializes a new instance of the <see cref="ObservableKeyedCollection{TKey, T}"/> class that contains elements |
| | | 45 | | /// </summary> |
| | | 46 | | /// <param name="list">The list whose elements are copied to the new collection.</param> |
| | | 47 | | /// <param name="comparer">The optional comparer used to compare keys.</param> |
| | | 48 | | /// <param name="dictionaryCreationThreshold">Minimum items before creating dictionary. 0 = always create.</param> |
| | | 49 | | protected ObservableKeyedCollection(IEnumerable<T> list, IEqualityComparer<TKey>? comparer = null, int dictionaryCre |
| | 72 | 50 | | : base(list) |
| | | 51 | | { |
| | 72 | 52 | | Comparer = comparer ?? EqualityComparer<TKey>.Default; |
| | 72 | 53 | | _dictionaryCreationThreshold = dictionaryCreationThreshold; |
| | | 54 | | |
| | | 55 | | // Pre-create dictionary if we have items above threshold OR if threshold is 0 |
| | 72 | 56 | | if (_dictionaryCreationThreshold == 0 || Count > _dictionaryCreationThreshold) |
| | | 57 | | { |
| | 63 | 58 | | CreateDictionary(); |
| | | 59 | | } |
| | 72 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Gets the comparer used to compare keys. |
| | | 64 | | /// </summary> |
| | | 65 | | public IEqualityComparer<TKey> Comparer { get; } |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Gets the internal dictionary used for fast key lookups, if it has been created. |
| | | 69 | | /// </summary> |
| | 0 | 70 | | protected IDictionary<TKey, T>? Dictionary => _dict; |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Gets a value indicating whether gets whether the dictionary has been created. |
| | | 74 | | /// </summary> |
| | 15 | 75 | | protected bool IsDictionaryCreated => _dict is not null; |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// Gets the item associated with the specified key, or default if the key is not present. |
| | | 79 | | /// </summary> |
| | | 80 | | /// <param name="key">The key of the item to get.</param> |
| | | 81 | | /// <returns>The item associated with the specified key, or default if not found.</returns> |
| | | 82 | | public T? this[TKey key] |
| | | 83 | | { |
| | | 84 | | get |
| | | 85 | | { |
| | 30 | 86 | | ArgumentNullException.ThrowIfNull(key); |
| | | 87 | | |
| | | 88 | | // Fast path: Use dictionary if available |
| | 30 | 89 | | if (_dict is not null) |
| | | 90 | | { |
| | 27 | 91 | | return _dict.GetValueOrDefault(key); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | // Slow path: Linear search |
| | | 95 | | // Consider creating dictionary if we're searching frequently |
| | 3 | 96 | | EnsureDictionaryIfNeeded(); |
| | | 97 | | |
| | 3 | 98 | | return Items.FirstOrDefault(x => Comparer.Equals(GetKeyForItem(x), key)); |
| | | 99 | | } |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | /// <summary> |
| | | 103 | | /// Determines whether the collection contains an element with the specified key. |
| | | 104 | | /// </summary> |
| | | 105 | | /// <param name="key">The key to locate in the collection.</param> |
| | | 106 | | /// <returns>True if an element with the key exists; otherwise false.</returns> |
| | | 107 | | public bool Contains(TKey key) |
| | | 108 | | { |
| | 30 | 109 | | ArgumentNullException.ThrowIfNull(key); |
| | | 110 | | |
| | 30 | 111 | | if (_dict is not null) |
| | | 112 | | { |
| | 30 | 113 | | return _dict.ContainsKey(key); |
| | | 114 | | } |
| | | 115 | | |
| | 0 | 116 | | EnsureDictionaryIfNeeded(); |
| | 0 | 117 | | return Items.Any(x => Comparer.Equals(GetKeyForItem(x), key)); |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Attempts to get the value associated with the specified key. |
| | | 122 | | /// </summary> |
| | | 123 | | /// <param name="key">The key to locate.</param> |
| | | 124 | | /// <param name="value">The value if found.</param> |
| | | 125 | | /// <returns>True if the key was found; otherwise false.</returns> |
| | | 126 | | public bool TryGetValue(TKey key, out T? value) |
| | | 127 | | { |
| | 6 | 128 | | ArgumentNullException.ThrowIfNull(key); |
| | | 129 | | |
| | 6 | 130 | | if (_dict is not null) |
| | | 131 | | { |
| | 6 | 132 | | return _dict.TryGetValue(key, out value); |
| | | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | EnsureDictionaryIfNeeded(); |
| | | 136 | | |
| | 0 | 137 | | value = Items.FirstOrDefault(x => Comparer.Equals(GetKeyForItem(x), key)); |
| | 0 | 138 | | return value is not null; |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Attempts to add an item to the collection if its key is not already present. |
| | | 143 | | /// </summary> |
| | | 144 | | /// <param name="item">The item to add.</param> |
| | | 145 | | /// <returns>True if the item was added; false if the key was null or already exists.</returns> |
| | | 146 | | public bool TryAdd(T item) |
| | | 147 | | { |
| | 9 | 148 | | var key = GetKeyForItem(item); |
| | 9 | 149 | | if (key is null) return false; |
| | | 150 | | |
| | 9 | 151 | | EnsureDictionaryIfNeeded(); |
| | | 152 | | |
| | 9 | 153 | | if (_dict?.ContainsKey(key) == true) |
| | 6 | 154 | | return false; |
| | | 155 | | |
| | 3 | 156 | | Add(item); |
| | 3 | 157 | | return true; |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Removes the item with the specified key from the collection. |
| | | 162 | | /// </summary> |
| | | 163 | | /// <param name="key">The key of the item to remove.</param> |
| | | 164 | | /// <returns>True if the item was found and removed; otherwise false.</returns> |
| | | 165 | | public bool Remove(TKey key) |
| | | 166 | | { |
| | 9 | 167 | | ArgumentNullException.ThrowIfNull(key); |
| | | 168 | | |
| | | 169 | | // Fast path with dictionary |
| | 9 | 170 | | if (_dict is not null) |
| | | 171 | | { |
| | 9 | 172 | | return _dict.TryGetValue(key, out var item) && Remove(item); |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | // Slow path without dictionary |
| | 0 | 176 | | for (var i = 0; i < Items.Count; i++) |
| | | 177 | | { |
| | 0 | 178 | | if (!Comparer.Equals(GetKeyForItem(Items[i]), key)) continue; |
| | 0 | 179 | | RemoveItem(i); |
| | 0 | 180 | | return true; |
| | | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | return false; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Changes the key associated with an existing item in the collection. |
| | | 188 | | /// </summary> |
| | | 189 | | /// <param name="item">The item whose key is changing.</param> |
| | | 190 | | /// <param name="newKey">The new key to associate with the item.</param> |
| | | 191 | | protected void ChangeItemKey(T item, TKey? newKey) |
| | 0 | 192 | | => ChangeItemKey(item, newKey, default); |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Changes the key associated with an existing item in the collection. |
| | | 196 | | /// </summary> |
| | | 197 | | /// <param name="item">The item whose key is changing.</param> |
| | | 198 | | /// <param name="newKey">The new key to associate with the item.</param> |
| | | 199 | | /// <param name="oldKey">The old key to remove. If default, GetKeyForItem is used.</param> |
| | | 200 | | protected void ChangeItemKey(T item, TKey? newKey, TKey? oldKey) |
| | | 201 | | { |
| | 3 | 202 | | if (!ContainsItem(item)) |
| | 0 | 203 | | return; |
| | | 204 | | |
| | | 205 | | // Use provided oldKey or get it from item |
| | 3 | 206 | | oldKey ??= GetKeyForItem(item); |
| | | 207 | | |
| | 3 | 208 | | if (Comparer.Equals(oldKey, newKey)) |
| | 0 | 209 | | return; |
| | | 210 | | |
| | 3 | 211 | | if (newKey is not null) |
| | | 212 | | { |
| | 3 | 213 | | AddKeyInternal(newKey, item); |
| | | 214 | | } |
| | | 215 | | |
| | 3 | 216 | | if (oldKey is not null) |
| | | 217 | | { |
| | 3 | 218 | | RemoveKeyInternal(oldKey); |
| | | 219 | | } |
| | 3 | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <inheritdoc /> |
| | | 223 | | protected override void ClearItems() |
| | | 224 | | { |
| | 3 | 225 | | _dict?.Clear(); |
| | 3 | 226 | | base.ClearItems(); |
| | 3 | 227 | | } |
| | | 228 | | |
| | | 229 | | /// <summary> |
| | | 230 | | /// When implemented in a derived class, returns the key for the specified item. |
| | | 231 | | /// </summary> |
| | | 232 | | /// <param name="item">The item to extract the key from.</param> |
| | | 233 | | /// <returns>The key for the specified item, or null if no key is associated.</returns> |
| | | 234 | | protected abstract TKey? GetKeyForItem(T item); |
| | | 235 | | |
| | | 236 | | protected override void InsertItem(int index, T item) |
| | | 237 | | { |
| | 360 | 238 | | var key = GetKeyForItem(item); |
| | | 239 | | |
| | | 240 | | // Add to base collection first |
| | 360 | 241 | | base.InsertItem(index, item); |
| | | 242 | | |
| | | 243 | | // Then handle dictionary |
| | 360 | 244 | | if (key is not null) |
| | | 245 | | { |
| | | 246 | | // Check threshold AFTER item is added |
| | | 247 | | // Special case: if threshold is 0, always use dictionary |
| | 357 | 248 | | if (_dict is not null || |
| | 357 | 249 | | (_dictionaryCreationThreshold == 0 && Count > 0) || |
| | 357 | 250 | | Count > _dictionaryCreationThreshold) |
| | | 251 | | { |
| | 336 | 252 | | if (_dict is null) |
| | | 253 | | { |
| | 3 | 254 | | CreateDictionary(); |
| | | 255 | | } |
| | | 256 | | else |
| | | 257 | | { |
| | 333 | 258 | | _dict.Add(key, item); |
| | | 259 | | } |
| | | 260 | | } |
| | | 261 | | } |
| | 357 | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Inserts an item directly into the underlying Items collection without dictionary handling. |
| | | 266 | | /// Use with caution - this bypasses key tracking. |
| | | 267 | | /// </summary> |
| | | 268 | | /// <param name="index">The position at which to insert the item.</param> |
| | | 269 | | /// <param name="item">The item to insert.</param> |
| | 0 | 270 | | protected void InsertItemInItems(int index, T item) => base.InsertItem(index, item); |
| | | 271 | | |
| | | 272 | | /// <summary> |
| | | 273 | | /// Adds the elements of the specified collection to the end of the collection. |
| | | 274 | | /// Overridden to ensure dictionary is updated. |
| | | 275 | | /// </summary> |
| | | 276 | | /// <param name="items">The collection whose elements should be added.</param> |
| | | 277 | | public override void AddRange(IEnumerable<T> items) |
| | | 278 | | { |
| | 9 | 279 | | ArgumentNullException.ThrowIfNull(items); |
| | | 280 | | |
| | 9 | 281 | | var initialCount = Count; |
| | | 282 | | |
| | | 283 | | // Call parent AddRange which adds to Items directly |
| | 9 | 284 | | base.AddRange(items); |
| | | 285 | | |
| | | 286 | | // Now update dictionary with all new items |
| | 9 | 287 | | if (Count > initialCount) |
| | | 288 | | { |
| | | 289 | | // Check if we should create dictionary |
| | 9 | 290 | | if (_dict is null && (_dictionaryCreationThreshold == 0 || Count > _dictionaryCreationThreshold)) |
| | | 291 | | { |
| | | 292 | | // Create dictionary and it will include all items |
| | 0 | 293 | | CreateDictionary(); |
| | | 294 | | } |
| | 9 | 295 | | else if (_dict is not null) |
| | | 296 | | { |
| | | 297 | | // Dictionary exists, add only the new items |
| | | 298 | | // Items were added from initialCount to Count-1 |
| | 66 | 299 | | for (var i = initialCount; i < Count; i++) |
| | | 300 | | { |
| | 24 | 301 | | var item = Items[i]; |
| | 24 | 302 | | var key = GetKeyForItem(item); |
| | 24 | 303 | | if (key is not null) |
| | | 304 | | { |
| | 24 | 305 | | _dict.TryAdd(key, item); // Use TryAdd to avoid exceptions on duplicates |
| | | 306 | | } |
| | | 307 | | } |
| | | 308 | | } |
| | | 309 | | } |
| | 9 | 310 | | } |
| | | 311 | | |
| | | 312 | | /// <summary> |
| | | 313 | | /// Removes the items with the specified keys from the collection. |
| | | 314 | | /// </summary> |
| | | 315 | | /// <param name="keys">The keys of the items to remove.</param> |
| | | 316 | | /// <returns>The number of items removed.</returns> |
| | | 317 | | public int RemoveRange(IEnumerable<TKey> keys) |
| | | 318 | | { |
| | 0 | 319 | | ArgumentNullException.ThrowIfNull(keys); |
| | | 320 | | |
| | 0 | 321 | | var set = new HashSet<TKey>(keys, Comparer); |
| | | 322 | | |
| | 0 | 323 | | var removedCount = 0; |
| | | 324 | | |
| | | 325 | | // First, remove from dictionary |
| | 0 | 326 | | if (_dict is not null) |
| | | 327 | | { |
| | 0 | 328 | | removedCount += set.Count(key => _dict.Remove(key)); |
| | | 329 | | } |
| | | 330 | | |
| | | 331 | | // Then, remove from base items collection |
| | 0 | 332 | | for (var i = Items.Count - 1; i >= 0; i--) |
| | | 333 | | { |
| | 0 | 334 | | var key = GetKeyForItem(Items[i]); |
| | 0 | 335 | | if (key is not null && set.Contains(key)) |
| | | 336 | | { |
| | 0 | 337 | | RemoveItem(i); |
| | 0 | 338 | | removedCount++; |
| | | 339 | | } |
| | | 340 | | } |
| | | 341 | | |
| | 0 | 342 | | return removedCount; |
| | | 343 | | } |
| | | 344 | | |
| | | 345 | | protected override void RemoveItem(int index) |
| | | 346 | | { |
| | 6 | 347 | | var key = GetKeyForItem(Items[index]); |
| | | 348 | | |
| | 6 | 349 | | base.RemoveItem(index); |
| | | 350 | | |
| | 6 | 351 | | if (key is not null) |
| | | 352 | | { |
| | 6 | 353 | | RemoveKeyInternal(key); |
| | | 354 | | } |
| | 6 | 355 | | } |
| | | 356 | | |
| | | 357 | | protected override void SetItem(int index, T item) |
| | | 358 | | { |
| | 3 | 359 | | var newKey = GetKeyForItem(item); |
| | 3 | 360 | | var oldKey = GetKeyForItem(Items[index]); |
| | | 361 | | |
| | 3 | 362 | | if (Comparer.Equals(oldKey, newKey)) |
| | | 363 | | { |
| | 0 | 364 | | if (newKey is not null && _dict is not null) |
| | | 365 | | { |
| | 0 | 366 | | _dict[newKey] = item; |
| | | 367 | | } |
| | | 368 | | } |
| | | 369 | | else |
| | | 370 | | { |
| | 3 | 371 | | if (newKey is not null) |
| | | 372 | | { |
| | 3 | 373 | | EnsureDictionaryIfNeeded(); |
| | 3 | 374 | | AddKeyInternal(newKey, item); |
| | | 375 | | } |
| | | 376 | | |
| | 3 | 377 | | if (oldKey is not null) |
| | | 378 | | { |
| | 3 | 379 | | RemoveKeyInternal(oldKey); |
| | | 380 | | } |
| | | 381 | | } |
| | | 382 | | |
| | 3 | 383 | | base.SetItem(index, item); |
| | 3 | 384 | | } |
| | | 385 | | |
| | | 386 | | /// <summary> |
| | | 387 | | /// Ensures the dictionary is created if the collection size warrants it. |
| | | 388 | | /// </summary> |
| | | 389 | | private void EnsureDictionaryIfNeeded() |
| | | 390 | | { |
| | 15 | 391 | | if (_dict is null && Count >= _dictionaryCreationThreshold) |
| | | 392 | | { |
| | 0 | 393 | | CreateDictionary(); |
| | | 394 | | } |
| | 15 | 395 | | } |
| | | 396 | | |
| | | 397 | | /// <summary> |
| | | 398 | | /// Forces creation of the dictionary regardless of size. |
| | | 399 | | /// </summary> |
| | | 400 | | protected void CreateDictionaryNow() |
| | | 401 | | { |
| | 3 | 402 | | if (_dict is null) |
| | | 403 | | { |
| | 3 | 404 | | CreateDictionary(); |
| | | 405 | | } |
| | 3 | 406 | | } |
| | | 407 | | |
| | | 408 | | private bool ContainsItem(T item) |
| | | 409 | | { |
| | 3 | 410 | | var key = GetKeyForItem(item); |
| | | 411 | | |
| | 3 | 412 | | return _dict is null || key is null |
| | 3 | 413 | | ? Items.Contains(item) |
| | 3 | 414 | | : _dict.TryGetValue(key, out var itemInDict) && EqualityComparer<T>.Default.Equals(itemInDict, item); |
| | | 415 | | } |
| | | 416 | | |
| | | 417 | | /// <summary> |
| | | 418 | | /// Internal add key without additional locking (assumes already locked). |
| | | 419 | | /// </summary> |
| | | 420 | | private void AddKeyInternal(TKey key, T item) |
| | | 421 | | { |
| | 6 | 422 | | if (_dict is null) |
| | | 423 | | { |
| | 0 | 424 | | CreateDictionary(); |
| | | 425 | | } |
| | | 426 | | |
| | 6 | 427 | | _dict?.Add(key, item); |
| | 6 | 428 | | } |
| | | 429 | | |
| | | 430 | | /// <summary> |
| | | 431 | | /// Internal remove key without additional locking (assumes already locked). |
| | | 432 | | /// </summary> |
| | 12 | 433 | | private void RemoveKeyInternal(TKey key) => _dict?.Remove(key); |
| | | 434 | | |
| | | 435 | | private void CreateDictionary() |
| | | 436 | | { |
| | | 437 | | // Pre-allocate with current count + some headroom |
| | 69 | 438 | | var capacity = Math.Max(Count, 16); |
| | 69 | 439 | | _dict = new(capacity, Comparer); |
| | | 440 | | |
| | 180 | 441 | | foreach (var item in Items) |
| | | 442 | | { |
| | 21 | 443 | | var key = GetKeyForItem(item); |
| | 21 | 444 | | if (key is not null) |
| | | 445 | | { |
| | | 446 | | // Use TryAdd to avoid exceptions if duplicate keys exist |
| | 21 | 447 | | _dict.TryAdd(key, item); |
| | | 448 | | } |
| | | 449 | | } |
| | 69 | 450 | | } |
| | | 451 | | |
| | | 452 | | /// <summary> |
| | | 453 | | /// Gets statistics about the dictionary usage. |
| | | 454 | | /// </summary> |
| | 3 | 455 | | protected (bool Created, int Count, int Capacity) GetDictionaryStats() => _dict is null ? (false, 0, 0) : (true, _di |
| | | 456 | | } |
| | | 457 | | |