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