gpt4 book ai didi

c# - ToDictionary 没有按预期工作

转载 作者:太空狗 更新时间:2023-10-29 20:06:09 25 4
gpt4 key购买 nike

给定以下代码,我无法返回字典。

[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, 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);

关于c# - ToDictionary 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4247231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com