I have a dictionary as follows:
public enum Role { Role1, Role2, Role3, }
public enum Action { Action1, Action2, Action3, }
var dictionary = new Dictionary<Role, List<Action>>();
dictionary.Add(RoleType.Role1, new Action [] { Action.Action1, Action.Action2 }.ToList());
Now I want to be able to construct a read-only dictionary whose value type is also read-only as follows:
var readOnlyDictionary = new ReadOnlyDictionary<Role, ReadOnlyCollection<Action>>(dictionary);
The last line obviously causes a compile-time error due to the differences in TValue
types.
Using a List<TValue>
is also necessary since the original dictionary is programatically populated from an external source.
Is there an easy way to perform this conversion?
Converting a Dictionary to a ReadOnlyDictionary is as simple as passing the regular dictionary as a parameter to the constructor of ReadOnlyDictionary:
var myDict = new Dictionary<K, V>();
var myReadOnlyDict = new ReadOnlyDictionary<K, V>(myDictionary);
One possibility (probably suboptimal for large collections) would be to construct a new Dictionary
object of the desired type (using the Enumerable.ToDictionary overload) and use the List.AsReadOnly() extension like this:
var readOnlyDictionary =
new ReadOnlyDictionary<Role, ReadOnlyCollection<Action>>
(dictionary.ToDictionary(k => k.Key, v => v.Value.AsReadOnly()));
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