LINQ Group For a project in 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()
    };

It all works and makes sense.

What I'm trying to achieve is to group a syntax type instead of an anonymous type.

For example, I have a ProductColour class, and I would like to Group in List<ProductColour>

Is it possible?

thank

+3
source share
2 answers

EDIT: Well, I read your post completely wrong. In appearance, you do not want to group by another type - you want to project each element of the group to a different type. Here is what I will 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();
+3
source

LinqToSql ( , - IGrouping<T, U>, ). , LinqToSql , 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() 
    };
+2

Source: https://habr.com/ru/post/1747509/


All Articles