0

I need to create a class that:

  • manipulates a Dictionary<int, List<string>> internally
  • exposes it as a property of type IReadOnlyDictionary<int, IEnumerable<string>>

The latter requirement cannot be changed unfortunately. Due to the (understandable) limitations of covariance in C#, the following does not work:

private Dictionary<int, List<string>> things;
public IReadOnlyDictionary<int, IEnumerable<string>> Things => things; // compile time error

The class needs to mutate the dictionary and the lists, so I cannot change the private field to be of the interface type.

What is the most succinct way, preferably using Linq, to convert a Dictionary<int, List<string>> to an IReadOnlyDictionary<int, IEnumerable<string>>?

Botond Balázs
  • 2,512
  • 1
  • 24
  • 34
  • 1
    Why not keep it as `private Dictionary> things;` and then cast the value back to `List` internally when you want to modify the collection? – Igor Jan 10 '17 at 16:39
  • Could it be that you are looking for : `... => Things.ToDictionary(k => k.Key, k => k.Value);` (an implicit cast of values) – Fabjan Jan 10 '17 at 16:40
  • @Igor because I need to add elements to the lists – Botond Balázs Jan 10 '17 at 16:41
  • @Fabjan That would make a copy of the dictionary, but I think you would also need `Things.ToDictionary(k => k.Key, k => k.Value.AsEnumerable())` or a cast on the value to `IEnumerable` to get the right dictionary type. – D Stanley Jan 10 '17 at 16:41
  • 2
    ... which is why I suggested the cast. Internally (in the class) you know its a `List`. You can also add a convenience method if you want in the class. Example code inside that class: `void someThingThatAdds(){ ((List) this.things[32]).Add("new string");` – Igor Jan 10 '17 at 16:41
  • Thanks Igor, I could solve it this way, even though I had to specify the generic argumetns explicitly. – Botond Balázs Jan 10 '17 at 16:45

0 Answers0