Linq相当于一个表中的sql语句,但包括基于该表中的组的计数

时间:2013-10-03 09:45:37

标签: sql vb.net linq

对于可怕的标题,我不知道使用的正确术语。

我有一个简单的表格(称为材料):

Id       int
Desc     Varchar(50)
MainType Varchar(20)
SubType  Varchar(20)

一些示例数据:

ID     Desc                    Maintype     SubType
1      Aluminium 3003          Metal        Aluminium
2      Bamboo                  Wood         Softwood
3      Cellulose Acetate       Polymer      CA
4      Cork                    Wood         Composite
5      Stainless Steel         Metal        Steel
6      Tinplate                Metal        Steel
7      PA (Type 11, Unfilled)  Polymer      PA
8      PA (Type 12, Unfilled)  Polymer      PA
9      PA (Type 46, Extrusion) Polymer      PA
10     Palm                    Wood         Softwood

我只想要一个有序的(按主要类型,子类型)材料列表(未分组),并包括数据集中每种材料主要类型和子类型的出现次数,如下所示:

ID     Desc                    Maintype     SubType    CountMain   CountSub
1      Aluminium 3003          Metal        Aluminium  3           1
5      Stainless Steel         Metal        Steel      3           2
6      Tinplate                Metal        Steel      3           2
3      Cellulose Acetate       Polymer      CA         4           1
7      PA (Type 11, Unfilled)  Polymer      PA         4           3
8      PA (Type 12, Unfilled)  Polymer      PA         4           3
9      PA (Type 46, Extrusion) Polymer      PA         4           3
4      Cork                    Wood         Composite  3           1
2      Bamboo                  Wood         Softwood   3           2
10     Palm                    Wood         Softwood   3           2

在SQL中,这是一个轻而易举的事:

SELECT Id
      ,MaterialName
      ,MaterialType
      ,MaterialSubType
      ,(select count(id) from materials m2 where m2.materialType=m1.materialType) as CountMain
      ,(select count(id) from materials m2 where m2.materialSubType=m1.materialSubType) as CountSub
  FROM materials m1
  order by materialType, MaterialSubType 

然而在Linq,我无法靠近它。这可能是因为我使用vb并且在group和into中存在一些语法上的困难。我甚至无法得到linq表达式的清晰汇编,因为我无法解决由“group”,“into”和“count”引起的恶魔上下文问题。由于我不知道我用于“计数”结果的subQueries的正确技术术语,我找不到任何执行此操作的示例。也许是因为我做错了!

我确信对于理解linq查询的人来说会非常简单 - 如果有在线教程或某些东西可以告诉我如何实现这一点,我会很感激指针或如何做到这一点的简要说明在LINQ请。

1 个答案:

答案 0 :(得分:0)

Sods法律,我发布后就把它解决了!

from mat in materials 
order by mat.mainType, mat.subType
select new with {
    mat.Id,
    mat.MaterialName,
    mat.MainType,
    mat.SubType,
    .countMain = (Aggregate m2 in materials
                    where m2.MainType=mat.MainType
                    into Count()),
    .countSub = (Aggregate m2 in materials
                    where m2.SubType=mat.SubType
                    into Count())
}