如何返回Dictionary <int,object>?

Dav*_*edy 4 c# linq dictionary iqueryable anonymous-types

这有效:

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

但出于某种原因,这不是:

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

这也不起作用:

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

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

Cannot convert expression type 'System.Collections.Generic.Dictionary<int,{Description:string}>' to return type 'System.Collections.Generic.IDictionary<int,object>'
Run Code Online (Sandbox Code Playgroud)

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

...如果你的数据从一个IEnumerable或IQueryable的源来了,你可以使用LINQ ToDictionary运营商出突起从序列元素所需要的密钥和(匿名类型)值,得到一个:

var intToAnon = sourceSequence.ToDictionary(
    e => e.Id,
    e => new { e.Column, e.Localized });
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?

Mat*_*zer 7

如何明确地将字典值转换为object

return products.ToDictionary( p => p.Id, p => (object)new { Description = p.Description } )
Run Code Online (Sandbox Code Playgroud)

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

也许如果IDictionary<TKey, TValue>支持协变 TValue ......


Yon*_*Nir 6

像您一样使用匿名类型是一种不好的做法。不要尝试将它们包装为object. 如果您需要匿名类型,请在定义它们的相同方法上下文中使用它们。

只是改变你的方法怎么样:

public IDictionary<int, object> GetProducts( int departmentID )
{
    return new Dictionary<int, object>
                {
                    { 1, "Something"},
                    { 2, "Whatever"},
                };
}
Run Code Online (Sandbox Code Playgroud)

然后将对象转换回字符串?

当然,这是假设您不能将类型更改为 IDictionary<int, string>