Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a ReadOnlyCollection<T> of the Keys in a Dictionary<T, S>

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.

like image 945
Joel in Gö Avatar asked Nov 12 '08 14:11

Joel in Gö


People also ask

What is ReadOnlyCollection?

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.

How do you make a method return a read-only collection?

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.

What is read-only dictionary C#?

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>

What is a key in C#?

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♯.


1 Answers

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> :)

like image 152
Jb Evain Avatar answered Oct 24 '22 11:10

Jb Evain