vb.net 使用 GROUP BY 对多个字段、SUM 和 COUNT 进行 Linq 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33364411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:31:56  来源:igfitidea点击:

Linq query with GROUP BY on multiple fields, SUM and COUNT

vb.netlinq

提问by Bastien Vandamme

I'm trying to use a LINQ SQL to query my database.

我正在尝试使用 LINQ SQL 来查询我的数据库。

Let's say I have some data that looks like this:

假设我有一些看起来像这样的数据:

var1 var2 var3 qty
1    a    1a   50
1    a    1a   25
2    b    2b   10
2    b    2b   15
2    b    2b   10
3    a    3a   25

I know how to format my query in SQL. It would be something like this:

我知道如何在 SQL 中格式化我的查询。它会是这样的:

SELECT var1, var2, var3, count(*) AS count, sum(qty) As quantity
    FROM MyTable
    GROUP BY var1, var2, var3

In this case the output would be something like this:

在这种情况下,输出将是这样的:

var1 var2 var3 Count Qty
1    a    1a   2     75
2    b    2b   3     35
3    a    3a   1     25

How can I do the same thing with LINQ in vb.net

如何在 vb.net 中用 LINQ 做同样的事情

Dim groups = From j In MyTable
             Group By j.var1, j.var2, j.var3 Into g
             Select new {var1 = g.var1, 
                         var2 = g.var2, 
                         var3 = g.var3, 
                         quantity = sum(g.qty),
                         count = count(*)}

That's not quite right, but I think it's close. I don't understand the syntax of the group by in VB.NET.

这不太正确,但我认为它很接近。我不明白 VB.NET 中 group by 的语法。

采纳答案by Tim Schmelter

You want to group by an anonymous type, this is the syntax in VB.NET (note the Key):

您想按匿名类型分组,这是 VB.NET 中的语法(注意Key):

Dim groups = 
    From j In MyTable
    Group By x = New With {Key .var1 = j.var1, Key .var2 = j.var2, Key .var3 = j.var3} Into g = Group
    Select New With {
        .var1 = x.var1,
        .var2 = x.var2,
        .var3 = x.var3,
        .quantity = g.Sum(Function(r) r.qty),
        .count = g.Count()
    }

回答by Rahul Singh

You will have to use anonymous typelike this:-

您将不得不使用这样的匿名类型:-

Group j By Key = New With { Key .Var1 = j.var1,
                            Key .Var2 = j.var2,
                            Key .Var3 = j.var3 } Into Group
Select New With { .var1 = Key.Var1,
                  .var2 = Key.Var2,
                  .var3 = Key.Var3,
                  .quantity = Group.Sum(Function(x) x.qty),
                  .count = Group.Count()
                }