linqef-core-5.0c#-9.0ef-core-6.0

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

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