简体   繁体   English

linq to sql复杂查询,分组依据

[英]linq to sql complex query with group by

I have a table called "Articles". 我有一个名为“文章”的表格。

it includes the following field: 它包括以下字段:

ArticleIndex, ArticleLevel, ArticleParentIndex. ArticleIndex,ArticleLevel,ArticleParentIndex。

I made query which returns all the articles with ArticleLevel=1 - let's call it query1. 我进行了查询,该查询返回了ArticleLevel = 1的所有文章-我们将其称为query1。 The query which returns all the articles with ArticleLevel=2 - query2. 该查询返回所有ArticleLevel = 2的文章-query2。

I would like to have a query that would return Articles of level=1 with at least one child article (the child articles have level=2), and also the number of child articles. 我想查询一个查询,该查询将返回带有至少一个子商品(子商品的级别为2)的level = 1的商品,以及子商品的数量。

So far I have the following query: 到目前为止,我有以下查询:

var filteredItemsGrouped = from i in filteredItems
                           group i by i.ArticleParentIndex into g
                           select new { Node = g, NodeItemsCount = g.Count() };

and then, in order to get the actual articles with level=1 I do: 然后,为了获得级别= 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
            });
        }

This process is too expensive. 这个过程太昂贵了。 Is it possible to acheive the same with one query (instead of retreiving by article index every time)? 是否可以通过一个查询达到相同的效果(而不是每次都按文章索引检索)?

Hope I'm clear enough... 希望我足够清楚...

this should do the trick: 这应该可以解决问题:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM