Reputation: 27
I have a method that creates a Dictionary<int, List<int>
and I want the method to return an IReadOnlyDictionary<int,IReadOnlyList<int>>
.
I tried with return Example as IReadOnlyDictionary<int, IReadOnlyList<int>>;
but returns Null
I did it creating a new Dictionary<int, IReadOnlyList<int>> Test
and copying all the values of the List AsReadOnly and then
IReadOnlyDictionary<int, IReadOnlyList<int>> Result = Test;
What are other ways to achieve this and there is one that is better than the others ?
Upvotes: 1
Views: 482
Reputation: 37059
IReadOnlyDictionary<K, V>
is conveniently implemented by ReadOnlyDictionary<K, V>
:
Dictionary<int, List<int>> regularDictionary = new Dictionary<int, List<int>>();
var readOnlyDict = new ReadOnlyDictionary<int, List<int>>(regularDictionary);
If you want the lists in the values to be readonly as well, then you'll have to do the same thing with those lists that you did with the dictionary above: Create a new readonly collection for each one, and use that readonly collection type to reference it.
This code looks like awful garble, but it's not that bad if you break it down piece by piece. We'll do it in two stages to mute the horror. Part of the problem is... what do you name these things to differentiate them?
var regularDictWithReadOnlyCollections=
regularDictionary.ToDictionary(kvp => kvp.Key,
kvp => new ReadOnlyCollection<int>(kvp.Value));
var readOnlyDictOfReadOnlyCollections =
new ReadOnlyDictionary<int, ReadOnlyCollection<int>>(
regularDictWithReadOnlyCollections);
Upvotes: 3