LINQ Group By to project into a non-anonymous type?
I have the following LINQ example:
var colorDistribution =
from product in ctx.Products
group product by product.Col开发者_C百科or
into productColors
select
new
{
Color = productColors.Key,
Count = productColors.Count()
};
All this works and makes perfect sense.
What I'm trying to achieve is to group by into a strong type instead of anonymous type.
For example I have a ProductColour class and I would like to Group into a List<ProductColour>
Is this possible?
Thank you
EDIT: Okay, I'd completely misread your post. By the looks of it, you're not wanting to group by a different type - you're wanting to project each element of the group into a different type. Here's what I'd do:
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 does allow direct projection of the group into a type (after all, the group is just an IGrouping<T, U>
, a type). What LinqToSql can't do, is translate a constructor into SQL.
IQueryable<ProductColour> colorDistributionSql =
from product in ctx.Products
group product by product.Color
into productColors
select new ProductColour()
{
Color = productColors.Key,
Count = productColors.Count()
};
精彩评论