This works:
public IDictionary<int, object> GetProducts( int departmentID )
{
return new Dictionary<int, object>
{
{ 1, new { Description = "Something" } },
{ 2, new { Description = "Whatever" } },
};
}
But for some reason this doesn't:
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 } );
}
This doesn't work either:
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 } );
}
The compiler error (in both cases) is:
Cannot convert expression type 'System.Collections.Generic.Dictionary<int,{Description:string}>' to return type 'System.Collections.Generic.IDictionary<int,object>'
I assumed it was a problem with the ToDictionary Linq extension method, but according to this answer it should work since FindAll returns an 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 });
What gives?