2012-07-20 37 views
8

我的數據是這樣的:LINQ的日期得到的數據組的總和

read_date | T1 | T2 | 
15.02.2000 | 2 | 3 | 
16.02.2000 | 4 | 5 | 
15.03.2000 | 2 | 3 | 
16.03.2000 | 5 | 4 | 

我想mountly總和T1和T2的,就像這樣:

read_date | T1 | T2 | 
    02.2000 | 6 | 8 | 
    03.2000 | 7 | 7 | 

我試着寫類似這樣的:

var result = from s in meter_readings.Take(10) 
      group s by new { s.read_date} into g 
      select new 
      { 
       read_date = g.Key.read_date, 
       T1 = g.Sum(x => x.T1), 
       T2 = g.Sum(x => x.T2) 
      }; 

,但這並沒有給預期data.Is有什麼例子來給數據每小時總和,每天的數額等

感謝

回答

17

只應採取的年份和月份到分組時:

var result = 
    from s in meter_readings.Take(10) 
    group s by new { date = new DateTime(s.read_date.Year, s.read_date.Month, 1) } into g 
    select new 
    { 
     read_date = g.Key.date, 
     T1 = g.Sum(x => x.T1), 
     T2 = g.Sum(x => x.T2) 
    }; 
+0

非常感謝我的工作。對於日常數據,我應該寫「日」而不是「1」嗎? – 2012-07-20 07:15:19

+1

@AliRızaAdıyahşi是的,您可以使用'Day',或者您可以使用's.read_date.Date'而不是'new DateTime(s.read_date.Year,s.read_date.Month,s.read_date.Day)',會用較少的代碼給出相同的結果。 – phoog 2012-07-20 07:19:15

+0

太棒了!謝謝你。它幫助了我! – karbonphyber 2012-11-01 03:42:45

0

您當前組由意志集團由全日(即15.02.2000而不是02.2000)。這將最終創建一個每天而不是一個月的個人小組。

通過(假設它是約會對象)添加.Month到組:

group s by new { s.read_date.Month} into g 
+0

這隻適用於數據不超過12個月的情況;否則,它可以將2011年1月的數據和2012年1月的數據(所有這些日期的「月份」都是1)進行彙總。 – phoog 2012-07-20 07:13:30

5

首先,我以爲你可以跳過匿名類型:每月

var result = from s in meter_readings.Take(10) 
     group s by s.read_date into g 
     select new 
     { 
      read_date = g.Key, 
      T1 = g.Sum(x => x.T1), 
      T2 = g.Sum(x => x.T2) 
     }; 

二,組,使用一些價值,將uniq的uely識別月份,像這樣:

var result = from s in meter_readings.Take(10) 
     group s by s.read_date.ToString("yyyy.MM") into g 
     select new 
     { 
      read_month = g.Key, 
      T1 = g.Sum(x => x.T1), 
      T2 = g.Sum(x => x.T2) 
     }; 
0
static void Main() 
    { 
     var list = new List<meter_reading> 
         { 
          new meter_reading {Date = new DateTime(2000, 2, 15), T1 = 2, T2 = 3}, 
          new meter_reading {Date = new DateTime(2000, 2, 10), T1 = 4, T2 = 5}, 
          new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 2, T2 = 3}, 
          new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 5, T2 = 4} 
         }; 
      var sum = list 
      .GroupBy(x => GetFirstDayInMonth(x.Date)) 
      .Select(item => new meter_reading 
           { 
            Date = item.Key, 
            T1 = item.Sum(x => x.T1), 
            T2 = item.Sum(x => x.T2), 
           }).ToList(); 
    } 

    private static DateTime GetFirstDayInMonth(DateTime dateTime) 
    { 
     return new DateTime(dateTime.Date.Year, dateTime.Date.Month, 1); 
    } 
0
query.OrderBy(o => o.OrderDate) 
       .GroupBy(o => DbFunctions.CreateDateTime(o.OrderDate.Year, o.OrderDate.Month, 1, 0, 0, 0)) 
         .Select(group => new DateIncomeDto { Date = group.Key.Value, Income = group.Sum(item => item.PayFee ?? 0) }); 

它爲我工作!