鉴于以下代码,我无法返回字典.
[JsonProperty] public virtual IDictionary<Product,int> JsonProducts { get { return Products.ToDictionary<Product,int>(x => x.Key,v => v.Value); } } public virtual IDictionary<Product,int> Products { get; set; }
我收到以下错误..
‘System.Collections.Generic.IDictionary’ does not contain a definition for ‘ToDictionary’ and the best extension method overload ‘System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable,System.Func,System.Collections.Generic.IEqualityComparer)’ has some invalid arguments
cannot convert from ‘lambda expression’ to ‘System.Func’
cannot convert from ‘lambda expression’ to ‘System.Collections.Generic.IEqualityComparer
Product类没有什么特别之处.它被简单地定义为
class Product { public virtual int Id { get; set; } public virtual String Name { get; set; } }
解决方法
你为什么用
Products.ToDictionary<Product,v => v.Value)
而不仅仅是
Products.ToDictionary(x => x.Key,v => v.Value)
?
那是因为
public static Dictionary<TKey,TElement> ToDictionary<TSource,TKey,TElement>( this IEnumerable<TSource> source,Func<TSource,TKey> keySelector,TElement> elementSelector );
看一下数字(3)和泛型类型参数(Func)的类型.
这意味着你需要调用它:
Products.ToDictionary<KeyValuePair<Product,int>,Product,v => v.Value);