根据下面的代码,我很难返回字典。
[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.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable,
'System.Collections.Generic.IDictionary‘不包含'ToDictionary’的定义,最好的扩展方法重载ToDictionary System.Func,System.Collections.Generic.IEqualityComparer)‘有一些无效的参数不能从'lambda表达式’转换为'System.Func‘。
无法从“lambda表达式”转换为“System.Collections.Generic.IEqualityComparer”
Product没有什么特别之处。它被简单地定义为
class Product
{
public virtual int Id { get; set; }
public virtual String Name { get; set; }
}发布于 2010-11-22 15:50:53
你为什么要用
Products.ToDictionary<Product, int>(x => x.Key, 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,
Func<TSource, TElement> elementSelector
);查看泛型类型参数(Func)的数字(3)和类型。
这意味着你需要叫它:
Products.ToDictionary<KeyValuePair<Product, int>, Product, int>(x => x.Key, v => v.Value);发布于 2010-11-22 15:55:57
不要显式地指定泛型类型参数。ToDictionary<T1, T2>中的类型不是T1 = TKey和T2 = TValue (其中TKey是结果字典的键类型,TValue是字典中结果值的类型)。
接受两个泛型类型参数的ToDictionary的重载具有T = TSource和V = TKey。给你,TSource = KeyValuePair<Product, int>。此外,您正在调用具有两个参数的overload of ToDictionary。第一个参数是来自T1 -> T2的映射,第二个参数是IEqualityComparer<T2>。但x => x.Key不是从KeyValuePair<Product, int>到int的地图,v => v.Value也不是IEqualityComparer<int>。
当您没有显式地指定泛型类型参数时,编译器将检查x => x.Key和v => v.Value的类型,并查看ToDictionary的各种重载。有四个
ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>)ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, IEqualityComparer<TKey>)请注意,它可以立即排除1和4。因为它们有错误的参数数(分别为2和4,而调用的重载需要三个参数(第三个参数是隐藏的第一个参数,因为您正在调用扩展方法)。它可以排除2.因为最后一个参数不能为任何IEqualityComparer<T>转换为T。剩下最后一个过载了。它可以推断出x => x.Key是Func<KeyValuePair<Product, int>, Product>,v => v.Value是Func<KeyValuePair<Product, int>, int>,因此您正在调用
ToDictionary<KeyValuePair<Product, int>, Product, int>(
IEnumerable<KeyValuePair<Product, int>>,
Func<KeyValuePair<Product, int>, Product>,
Func<KeyValuePair<Product, int>, int>
)如果您想显式地指定类型参数,您必须说
Products.ToDictionary<KeyValuePair<Product, int>, Product, int>(
x => x.Key,
v => v.Value
);发布于 2010-11-22 16:03:31
如果您没有实际克隆产品实例,则只需执行以下操作:
public virtual IDictionary<Product, int> JsonProducts
{
get
{
return new Dictionary(Products);
}
}https://stackoverflow.com/questions/4247231
复制相似问题