私は次の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());
Dictionary<int?, int>
問題は、からを取得することToDictionary()
です。配置してnull値を事前にフィルタリングしても、のタイプをに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()
が、うまくいきませんでした。私はそれを少しグーグルで調べましたが、この問題を抱えている人は誰も見つけていませんが、特にEFとデータベースを使用している場合は、この状況が頻繁に発生する可能性があると思います。誰にも解決策がありますか?