跳過空值我有以下Product
類字典
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和數據庫工作時。任何人都有解決方案?
嘗試'p.CategoryId.Value'(即非空的)? –