2

I have a function that return a IDictionary<TKey, List<TValue> >.
I have another function that takes a IDictionary<TKey, IEnumerable<TValue> >.

I need to pass the return of the first function to the second function.
The compiler doesn't want to implicitlty convert the first into the second. So how could I convert the first into the second in O(1)?

I could always write a conversion function

public static IDictionary<TKey, IEnumerable<TValue>> ToIEnumerable<TKey, TValue>(this IDictionary<TKey, List<TValue>> source)
{
    return source.ToDictionary(s => s.Key, s => s.Value.AsEnumerable());
}

But I'm pretty sure this is not O(1), more like O(log n).

A related question here : Nested Interfaces: Cast IDictionary< TKey, IList< TValue > > to IDictionary< TKey, IEnumerable < TValue> >?

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122

1 Answers1

1

Consider your second function, the one that

 takes a IDictionary<TKey, IEnumerable<TValue> >

Now, if you give me a IDictionary<TKey, IEnumerable<TValue>>, one of the things I should be able to do is set the value of one of the keys to a new TValue[], right? After all, a TValue[] is an IEnumerable<TValue>, so it meets the constraint.

However, if somehow what you'd given me was (underneath the interface) a IDictionary<TKey, List<TValue>>, I definitely shouldn't be allowed to set the value of a key to a TValue[], since a TValue[] is not a List<TValue>!

This is exactly the problem in the question you have linked, of course.

Now, if you are happy to only ever read the parameter I pass you, you have a potential solution in moving from dictionaries to ILookup<TKey, TValue>, which is a bit like a read-only dictionary from a key to a list of values. If your methods respectively return and accept an ILookup<TKey, TValue> there's of course no problem.

AakashM
  • 62,551
  • 17
  • 151
  • 186
  • ILookup is a nice solution. Too bad it doesn't support empty list. – Cyril Gandon Apr 16 '13 at 10:29
  • @Scorpi0 is that a problem, given that when you look up a key, ["If the key is not found in the collection, an empty sequence is returned"](http://msdn.microsoft.com/en-us/library/bb292716.aspx) ? – AakashM Apr 16 '13 at 10:35
  • Not really. I have some logic based on the keys present in the dictionary. So if the key doesn't exist, well, I can't retrieve it easily. Side question : I can't install framework 4.5, but is the [ReadOnlyDictionary](http://msdn.microsoft.com/en-us/library/gg712875.aspx) could do the trick? I can't test it. – Cyril Gandon Apr 16 '13 at 10:39
  • @Scorpi0 I only gave that link as it is the canonical doc link, which goes to the most recent version. The Other Versions dropdown shows it's been present since .NET 3.5 (~= VS 2008). I suspect `ReadOnlyDictionary` might not be so easy to work with, but I haven't checked. – AakashM Apr 16 '13 at 11:20