0

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

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

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”引起的可怕的上下文问题。由于我不知道用于“计数”结果的子查询的正确技术术语,所以我找不到任何这样做的示例。也许是因为我做错了!

我敢肯定,对于了解 linq 查询的人来说,这将非常简单-如果有在线教程或可以向我展示如何实现此目的的东西,我将不胜感激,请提供有关如何在 LINQ 中执行此操作的指针或简要说明.

4

1 回答 1

0

草皮法,我在发布后就解决了!

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())
}
于 2013-10-03T10:04:30.077 回答