Home > Software design >  C# Dictionary elementSelector struggles with implicit IEnumerable cast
C# Dictionary elementSelector struggles with implicit IEnumerable cast

Time:04-30

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?

CodePudding user response:

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