VB.NET 和 LINQ - 在数据表中分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36699938/
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
VB.NET and LINQ - Group by in a DataTable
提问by rffs
I have a DataTable in VB.NET of this type:
我在 VB.NET 中有一个这种类型的 DataTable:
"Yr","Mnth","Period","Amount"
2016, 1, 2016-01, 550.36
2016, 1, 2016-01, 9000.79
2015, 12, 2015-12, 10000.30
2015, 12, 2015-12, 20
What I want to do is to aggregate this data using LINQ like I would in SQL language:
我想要做的是像使用 SQL 语言一样使用 LINQ 聚合这些数据:
SELECT Yr, Mnth, Period, SUM(Amount) AS Amount
GROUP BY Yr, Mnth, Period;
I have tried to use LINQ in VB.NET but haven't been able to get it right. Can someone give me some insight? Thank you.
我曾尝试在 VB.NET 中使用 LINQ,但一直无法正确使用。有人可以给我一些见解吗?谢谢你。
回答by Alex B.
Dim Amounts As New DataTable 'Your code to load actual DataTable here
Dim amountGrpByDates = From row In Amounts
Group row By dateGroup = New With {
Key .Yr = row.Field(Of Integer)("Yr"),
Key .Mnth = row.Field(Of Integer)("Mnth"),
Key .Period = row.Field(Of String)("Period")
} Into Group
Select New With {
Key .Dates = dateGroup,
.SumAmount = Group.Sum(Function(x) x.Field(Of Decimal)("Amount"))}
I assumed Yrand Mnthto be of type Integer, PeriodString and AmountDecimal.
Change the types if they differ from yours.
我假设Yr并且Mnth是整数、Period字符串和Amount十进制类型。如果类型与您的不同,请更改类型。
回答by dfdsfdsfsdf
Here's the C# code.
这是 C# 代码。
public static class program
{
static void Main(string[] args)
{
try
{
var table = new DataTable();
table.Columns.Add("year", typeof(string));
table.Columns.Add("month", typeof(string));
table.Columns.Add("period", typeof(string));
table.Columns.Add("amount", typeof(decimal));
var row = table.NewRow();
table.Rows.Add(row);
row["year"] = "2015";
row["month"] = "Jan";
row["period"] = "Period1";
row["amount"] = 100;
row = table.NewRow();
table.Rows.Add(row);
row["year"] = "2015";
row["month"] = "Jan";
row["period"] = "Period1";
row["amount"] = 50;
row = table.NewRow();
table.Rows.Add(row);
row["year"] = "2016";
row["month"] = "Fed";
row["period"] = "Period2";
row["amount"] = 5.55;
var result = (from r in table.AsEnumerable()
group r by new
{
Year = r.Field<string>("year"),
Month = r.Field<string>("month"),
Period = r.Field<string>("period"),
} into grp
select new {
grp.Key,
total = grp.Sum(p=> p.Field<decimal>("amount"))
});
foreach(var grp in result)
{
Console.WriteLine("{0} {1} {2} = {3}", grp.Key.Year, grp.Key.Month, grp.Key.Period, grp.total);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

