ToDictionary无法按预期工作

Cie*_*iel 7 c# linq

鉴于以下代码,我无法返回字典.

[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; }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误..

'System.Collections.Generic.IDictionary'不包含'ToDictionary'的定义和最佳扩展方法重载'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable,System.Func,System.Collections.Generic .IEqualityComparer)'有一些无效的参数

无法从'lambda表达式'转换为'System.Func'

无法从'lambda expression'转换为'System.Collections.Generic.IEqualityComparer

Product类没有什么特别之处.它被简单地定义为

class Product 
{
    public virtual int Id { get; set; }
    public virtual String Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

aba*_*hev 12

你为什么用

Products.ToDictionary<Product, int>(x => x.Key, v => v.Value)
Run Code Online (Sandbox Code Playgroud)

而不仅仅是

Products.ToDictionary(x => x.Key, v => v.Value)
Run Code Online (Sandbox Code Playgroud)


那是因为

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
);
Run Code Online (Sandbox Code Playgroud)

看一下数字(3)和泛型类型参数(Func)的类型.

这意味着你需要调用它:

Products.ToDictionary<KeyValuePair<Product, int>, Product, int>(x => x.Key, v => v.Value);
Run Code Online (Sandbox Code Playgroud)