Search code examples
c#.netdictionaryreadonly-collection

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


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?


Solution

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