Converting Dictionary<TKey, List<TValue>> to ReadOnlyDictionary<TKey, ReadOnlyCollection<TValue>>

Raheel Khan picture Raheel Khan · Mar 1, 2016 · Viewed 12.6k times · Source

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?

Answer

Brian Lacy picture Brian Lacy · Dec 31, 2019

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