Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Raheel Khan Avatar asked Mar 01 '16 21:03

Raheel Khan


2 Answers

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);
like image 179
Brian Lacy Avatar answered Sep 19 '22 13:09

Brian Lacy


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()));
like image 26
keenthinker Avatar answered Sep 21 '22 13:09

keenthinker