C# Dictionary elementSelector 与隐式 IEnumerable 转换斗争
C# Dictionary elementSelector struggles with implicit IEnumerable cast
简单场景:
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>
我的(可耻的)解决方法:
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => kv.Value.Where(x => true) // <-- back to being IEnumerable
);
我没有足够的勇气去尝试这个并面对不可预见的后果:
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => (IEnumerable<int>)kv.Value // <-- explicit cast
);
有什么建议吗?
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => kv.Value.Where(x => true).AsEnumerable() // <--
);
简单场景:
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>
我的(可耻的)解决方法:
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => kv.Value.Where(x => true) // <-- back to being IEnumerable
);
我没有足够的勇气去尝试这个并面对不可预见的后果:
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => (IEnumerable<int>)kv.Value // <-- explicit cast
);
有什么建议吗?
Dictionary<int, IEnumerable<int>> d2 = d.ToDictionary(
kv => kv.Key,
kv => kv.Value.Where(x => true).AsEnumerable() // <--
);