LINQ Group By投射到非匿名类型?

我有以下LINQ示例:

var colorDistribution = from product in ctx.Products group product by product.Color into productColors select new { Color = productColors.Key, Count = productColors.Count() }; 

所有这些都有效并且非常有意义。

我想要实现的是将其分组为强类型而不是匿名类型。

例如,我有一个ProductColour类,我想组成一个List

这可能吗?

谢谢

编辑:好的,我完全误读了你的post。 根据它的外观,您不希望其他类型进行分组 – 您希望将组中的每个元素投影不同的类型中。 这是我要做的:

 var colorDistributionSql = from product in ctx.Products group product by product.Color into productColors select new { Color = productColors.Key, Count = productColors.Count() }; var colorDistributionList = colorDistributionSql .AsEnumerable() .Select(x => new ProductColour(x.Color, x.Count)) .ToList(); 

LinqToSql允许将组直接投影到一个类型中(毕竟,该组只是一个IGrouping ,一个类型)。 LinqToSql不能做的是将构造函数转换为SQL。

 IQueryable colorDistributionSql = from product in ctx.Products group product by product.Color into productColors select new ProductColour() { Color = productColors.Key, Count = productColors.Count() };