My class contains a Dictionary<T, S> dict
, and I want to expose a ReadOnlyCollection<T>
of the keys. How can I do this without copying the Dictionary<T, S>.KeyCollection dict.Keys
to an array and then exposing the array as a ReadOnlyCollection
?
I want the ReadOnlyCollection
to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!
Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.
ReadOnlyCollection makes an array or List read-only. With this type from System. Collections. ObjectModel, we provide a collection of elements that cannot be changed.
We can make Collections object Read-Only by using unmodifiableCollection() and to make Map Read-Only we can use unmodifiableMap() method. This method accepts any of the collection objects and returns an unmodifiable view of the specified collection.
The IReadOnlyDictionary interface provides a read-only view of a dictionary and represents a read-only collection of key/value pairs. The following code snippet illustrates how you can define an IReadOnlyDictionary instance. public IReadOnlyDictionary<string, string> Dictionary { get; } = new Dictionary<string, string>
C-sharp major (or the key of C-sharp) is a major scale based on C♯, consisting of the pitches C♯, D♯, E♯, F♯, G♯, A♯, and B♯.
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>.
So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like:
var dictionary = ...;
var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)
);
Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With