C# Dictionary elementSelector struggles with implicit IEnumerable cast

83 views Asked by At

Simple scenario :

var d = new Dictionary<int, List<int>>();

Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
    kv => kv.Key,
    kv => kv.Value // <-- the problem
    );

.

ERROR  CS0029 : Cannot implicitly convert from List<string> to IEnumerable<string>

My (shameful) workaround :

Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
    kv => kv.Key,
    kv => kv.Value.Where(x => true) // <-- back to being IEnumerable
    );

I'm not bold enough to try this and face unforeseen consequences :

Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
    kv => kv.Key,
    kv => (IEnumerable<int>)kv.Value // <-- explicit cast
    );

Any advice?

1

There are 1 answers

0
jeancallisti On BEST ANSWER
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
    kv => kv.Key,
    kv => kv.Value.Where(x => true).AsEnumerable() // <--
    );