3

私は次の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)変更しません。また、匿名型を作成しようとしました:CategoryIdint

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データベースを使用している場合は、この状況が頻繁に発生する可能性があると思います。誰にも解決策がありますか?

4

4 に答える 4

7

これCategoryIdは nullable であるためです。Valueしたがって、最初にプロパティを選択する必要があります。

products.ToList()
        .Where(p => p.CategoryId.HasValue)
        .Select(p => p.CategoryId.Value)
        .GroupBy(i => i)
        .ToDictionary(g => g.Key, g => g.Count());
于 2012-11-19T10:12:05.350 に答える
5

単に使用する

products.ToList()
    .GroupBy(p => p.CategoryId)
    .Where(pgroup => pgroup.Key.HasValue)
    .ToDictionary(pgroup => pgroup.Key.Value, pgroup => pgroup.Count());
于 2012-11-19T10:10:44.153 に答える
4

これはどう?

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

匿名型の構文エラーに関しては、正しい構文は次のとおりです。

.Select(p => new { Key = p.Key ?? -1, Count = p.Count() })
于 2012-11-19T10:10:03.390 に答える
0

null 値を除外してから、の.Valueプロパティをint?グループ化キーとして使用する必要があります。

products.ToList()
        .Where(p => p.CategoryId.HasValue)
        .GroupBy(p => p.CategoryId.Value)
        .ToDictionary(pgroup => pgroup.key, pgroup => pgroup.Count());
于 2012-11-19T10:11:59.827 に答える