这个有效:
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扩展方法的问题,但根据这个答案,它应该可以工作,因为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 });
发生了什么事?
dynamic
,但它们都不是编译时安全的。最好创建一个具体的类,并将其用作结果值类型。 - D Stanley