在 vb.net 中使用 linq 分组数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13998258/
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-09 16:31:21  来源:igfitidea点击:

Datatable group by with linq in vb.net

vb.netlinqdatatablegroup-by

提问by Nick

I'm trying to get aggregate values from data table. But can't figure out how. Saw some examples in c#, but couldn't translate those to vb.net.

我正在尝试从数据表中获取聚合值。但想不通怎么办。在 c# 中看到了一些示例,但无法将它们转换为 vb.net。

I have data table

我有数据表

Month, campaign, sales, leads, gross
1           1                5         10       1000
1            2               0          5         0
2            1               2          0         300
2            2               1          3         200

I need to get a result :

我需要得到一个结果:

Month, sales, leads, gross
1           5        15       1000
2           3         3         500

I don't want to loop and combine values manually. Please help

我不想手动循环和组合值。请帮忙

回答by Tim Schmelter

You want to Group by Month? You can use Sumto sum the groups:

你想Group by Month吗?您可以使用Sum对组求和:

Dim query = From row In dt
        Group row By Month = row.Field(Of Int32)("Month") Into MonthGroup = Group
        Select New With {
            Key Month,
            .Sales = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Sales")),
            .Leads = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Leads")),
            .Gross = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Gross"))
       }

For Each x In query
    Console.WriteLine("Month:{0} {1} {2} {3}", x.Month, x.Sales, x.Leads, x.Gross)
Next

This is a mixture of Linq query- and method-syntax.

这是 Linq 查询和方法语法的混合体。