'C# Dictionary elementSelector struggles with implicit IEnumerable cast

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jeancallisti