2016-04-18 38 views
1

我有一个DataTable这种类型的VB.NET:VB.NET和LINQ - 集团由一个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 

我想要做的就是聚合使用LINQ这个数据就像我会在SQL语言:

SELECT Yr, Mnth, Period, SUM(Amount) AS Amount 
GROUP BY Yr, Mnth, Period; 

我试图在VB.NET中使用LINQ,但一直没能弄清楚它的正确性。 有人能给我一些见解吗? 谢谢。

+0

你到目前为止尝试过什么?您是否需要对来自“DataTable”的数据进行分组,或者可以将源数据分组吗? –

回答

1
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"))} 

我假定YrMnth为整数类型,Period字符串和Amount十进制的。 如果它们与您的不同,请更改它们的类型。

0

这里是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); 
     } 

    } 

}