2016-04-18 51 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); 
     } 

    } 

}