gpt4 book ai didi

c# - 如何返回 Dictionary

转载 作者:太空狗 更新时间:2023-10-30 00:14:27 25 4
gpt4 key购买 nike

这个有效:

public IDictionary<int, object> GetProducts( int departmentID )
{
return new Dictionary<int, object>
{
{ 1, new { Description = "Something" } },
{ 2, new { Description = "Whatever" } },
};
}

但由于某些原因,这不是:

public IDictionary<int, object> GetProducts( int departmentID )
{
var products = ProductRepository.FindAll( p => p.Department.Id == departmentID );

return products.ToDictionary( p => p.Id, p => new { Description = p.Description } );
}

这也行不通:

public IDictionary<int, object> GetProducts( int departmentID )
{
var products = ProductRepository.FindAll( p => p.Department.Id == departmentID );

return products.ToDictionary( p => p.Id, p => new { p.Description } );
}

编译器错误(在这两种情况下)是:

Cannot convert expression type 'System.Collections.Generic.Dictionary<int,{Description:string}>' to return type 'System.Collections.Generic.IDictionary<int,object>'

我认为这是 ToDictionary Linq 扩展方法的问题,但根据 this answer它应该可以工作,因为 FindAll 返回 IQueryable<Product> :

... if your data is coming from an IEnumerable or IQueryable source, you can get one using the LINQ ToDictionary operator and projecting out the required key and (anonymously typed) value from the sequence elements:

var intToAnon = sourceSequence.ToDictionary(
e => e.Id,
e => new { e.Column, e.Localized });

什么给了?

最佳答案

将字典值显式转换为 object 怎么样? ?

return products.ToDictionary( p => p.Id, p => (object)new { Description = p.Description } )

实际上,匿名对象是编译时随机创建的常规类的一个实例,因此它是一个对象,但属于某种特定类型。这就是为什么您不能期望隐式转换为 IDictionary<string, object> 的原因.

也许如果 IDictionary<TKey, TValue>会支持covariant TValue ...

关于c# - 如何返回 Dictionary<int, object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300911/

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