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?
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System. Collection.
We can get the value in the dictionary by using the key with the [] method in C#. We created a dictionary, mydictionary , with the Dictionary<string, string> class. After that, we retrieved the value of the Key 3 key in mydictionary with the [] method.
Access Dictionary Elements The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.
What about explictly casting the dictionary value to object
?
return products.ToDictionary( p => p.Id, p => (object)new { Description = p.Description } )
Actually, an anonymous object is an instance of a compile-time randomly-created regular class, thus it's an object but it's of some particular type. This is why you can't expect an implicit cast to IDictionary<string, object>
.
Maybe if IDictionary<TKey, TValue>
would support covariant TValue
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With