What is the .NET C# syntax for an ObservableCollection with an indexer? I would like an ObservableColletion and refer to the items by ordinal position or a string name. I know you the use this to denote an indexer but I don’t know how to put that in an ObservableCollection. Thanks
Thanks for the 4 answers. I know how create and ObservableCollection and I know how to create an indexer. I don’t know how to combine them. I am asking for sample code for an ObservableCollection with an ordinal and string index.
Thank again
ObservableCollection inherits from Collection, so it already has position-based indexing.
For string-based indexing, you can look into peoples implementations of ObservableDictionary.
Personally, for better performance, I’ve created a HashedObservableCollection deriving from ObservableCollection which contains a Dictionary of keys to indexes to speed lookup time. By overriding InsertItem, RemoveItem, and ClearItems, you keep the dictionary in sync.
In my example, the keys can be of any type but we assume the key never changes – if an item is replaced, it is replaced with an object with the same key. If you want to simplify this, you can replace TKey with String.
Code: