Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.Color
    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


1 Answers

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();
like image 96
Jon Skeet Avatar answered Sep 09 '25 04:09

Jon Skeet