[英]linq to sql complex query with group by
我有一个名为“文章”的表格。
它包括以下字段:
ArticleIndex,ArticleLevel,ArticleParentIndex。
我进行了查询,该查询返回了ArticleLevel = 1的所有文章-我们将其称为query1。 该查询返回所有ArticleLevel = 2的文章-query2。
我想查询一个查询,该查询将返回带有至少一个子商品(子商品的级别为2)的level = 1的商品,以及子商品的数量。
到目前为止,我有以下查询:
var filteredItemsGrouped = from i in filteredItems
group i by i.ArticleParentIndex into g
select new { Node = g, NodeItemsCount = g.Count() };
然后,为了获得级别= 1的实际文章,我这样做:
IList<ArticleNodeInfo> Nodes = new List<ArticleNodeInfo>();
foreach (var node in filteredItemsGrouped)
{
Nodes.Add(new ArticleNodeInfo
{
Node = articlesService.GetArticleByIndex((int)(node.Node.FirstOrDefault().ArticleParentIndex)),
NodeItemsCount = node.NodeItemsCount
});
}
这个过程太昂贵了。 是否可以通过一个查询达到相同的效果(而不是每次都按文章索引检索)?
希望我足够清楚...
这应该可以解决问题:
var articlesLevel1 = (
from al1 in Articles
join al2 in Articles on new
{
al1.ArticleIndex,
ArticleLevel = 2
} equals new
{
ArticleIndex = al2.ArticleParentIndex,
al2.ArticleLevel
} into g_al2
where (al1.ArticleLevel == 1) && g_al2.Any()
select new
{
ArticlesLevel1 = al1,
ArticlesLevel2Count = g_al2.Count()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.