簡體   English   中英

如何返回字典 <int, object> ?

[英]How can I return a Dictionary<int, object>?

這有效:

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>

...如果您的數據來自IEnumerable或IQueryable源,您可以使用LINQ ToDictionary運算符獲取一個,並從序列元素中突出顯示所需的鍵和(匿名類型)值:

 var intToAnon = sourceSequence.ToDictionary( e => e.Id, e => new { e.Column, e.Localized }); 

是什么賦予了?

那么明確地將字典值轉換為object呢?

return products.ToDictionary( p => p.Id, p => (object)new { Description = p.Description } )

實際上,匿名對象是編譯時隨機創建的常規類的實例,因此它是一個對象,但它是某種特定類型。 這就是為什么你不能指望隱式轉換為IDictionary<string, object>

也許如果IDictionary<TKey, TValue>支持協變 TValue ......

使用像你這樣的匿名類型是一種不好的做法。 不要嘗試將它們包裝為object 如果您需要匿名類型,請在您定義它們的相同方法上下文中使用它們。

如何改變你的方法:

public IDictionary<int, object> GetProducts( int departmentID )
{
    return new Dictionary<int, object>
                {
                    { 1, "Something"},
                    { 2, "Whatever"},
                };
}

然后將對象轉換回字符串?

當然,假設您不能只將類型更改為IDictionary<int, string>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM