LINQ Group By将其投影为非匿名类型? [英] LINQ Group By to project into a non-anonymous type?
本文介绍了LINQ Group By将其投影为非匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下LINQ示例:
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.
例如,我有一个ProductColour类,我想将它分组到一个 List< ProductColour>
For example I have a ProductColour class and I would like to Group into a List<ProductColour>
?
谢谢
Thank you
推荐答案
编辑:好的,我会完全误读你的帖子。从外观上看,你不想通过对不同类型进行分组 - 你希望将组中的每个元素都映射到一个不同类型的中。以下是我要做的:
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();
这篇关于LINQ Group By将其投影为非匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文