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>
:
...如果你的数据从一个IEnumerable或IQueryable的源来了,你可以使用LINQ ToDictionary运营商出突起从序列元素所需的关键的 和(匿名类型)值 得到一个:
var intToAnon = sourceSequence.ToDictionary( e => e.Id, e => new { e.Column, e.Localized });
是怎么回事?
要知道,你就得值转换为比对象做任何有用的事情其他东西。由于实际值是匿名类型,因此您需要使用反射或“动态”,这两者都不是编译时安全的。你最好创建一个具体的类并使用_that_作为结果值类型。 – 2014-12-04 18:23:29
那么,返回值被序列化为JSON,这非常有用。仅仅为了序列化JSON而创建模型对我来说似乎是多余的。 – 2014-12-04 18:29:39
正确 - 这是一个有效的用法。 – 2014-12-04 18:30:41