2012-11-19 46 views
3

跳過空值我有以下Product類字典 轉換字典<int, int?>通過LINQ

public class Product 
{ 
    public string Name { get; set; } 
    public float Price { get; set; }  
    public int? CategoryId { get; set; } 
} 

現在我都數不過來有多少Product爲每個CategoryId,並把它們放在一個Dictionary<int, int>。因此:

IQueryable<Product> products = _productServices.GetAll(); //return IQueryable<Product> 

Dictionary<int, int> productDict = products.ToList() 
              .GroupBy(p => p.CategoryId) 
              .ToDictionary(pgroup => pgroup.key, pgroup => pgroup.Count()); 

的問題是,我獲得來自ToDictionary()一個Dictionary<int?, int>。即使我通過放置Where(p => p.CategoryId != null)預過濾空值,我不會將CategoryId的類型更改爲int。我也試圖創建和匿名類型:

products.ToList() 
     .GroupBy(p => p.CategoryId) 
     .Select(p => new { p.key ?? -1, p.Count() } 
     .ToDictionary(pgroup => pgroup.key, pgroup => pgroup); 

但它給出了一個Invalid anonymous type member declarator錯誤。我也嘗試刪除ToList(),但沒有運氣。我google一下了一下,我還沒有發現有這個問題任何人,但我認爲這種情況可能會頻繁,尤其是EF數據庫工作時。任何人都有解決方案?

+0

嘗試'p.CategoryId.Value'(即非空的)? –

回答

7

這是因爲CategoryId是空的。所以,你需要選擇它首先是Value屬性:不是`p.CategoryId`

products.ToList() 
     .Where(p => p.CategoryId.HasValue) 
     .Select(p => p.CategoryId.Value) 
     .GroupBy(i => i) 
     .ToDictionary(g => g.Key, g => g.Count()); 
+2

+1包括*爲什麼*它不工作,不是簡單地解決它。 –

4

這個怎麼樣?

.ToDictionary(pgroup => pgroup.Key ?? -1, pgroup => pgroup.Count()); 

和關於與匿名類型的語法錯誤,正確的語法如下:

.Select(p => new { Key = p.Key ?? -1, Count = p.Count() }) 
+0

小點;該操作明確地說「跳過空值」 - 試圖包含它們是很好的,但你需要問'-1'是否已經是一個有效的值。 –

+0

@MarcGravell,你是對的,我錯過了那部分...... –

5

products.ToList() 
    .GroupBy(p => p.CategoryId) 
    .Where(pgroup => pgroup.Key.HasValue) 
    .ToDictionary(pgroup => pgroup.Key.Value, pgroup => pgroup.Count()); 
0

您需要過濾掉空值簡單地使用,並然後使用int?.Value屬性作爲分組鍵:

products.ToList() 
     .Where(p => p.CategoryId.HasValue) 
     .GroupBy(p => p.CategoryId.Value) 
     .ToDictionary(pgroup => pgroup.key, pgroup => pgroup.Count()); 
相關問題