LINQ Group By to project into a non-anonymous type?

纵饮孤独 提交于 2020-01-13 19:08:35

问题


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:


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();



回答2:


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() 
    };


来源:https://stackoverflow.com/questions/2927618/linq-group-by-to-project-into-a-non-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!