2013-01-19 127 views
8

我有以下類結構:LINQ的選擇組通過

public class PriceLog 
{ 
    public DateTime LogDateTime {get; set;} 
    public int Price {get; set;} 
} 

對於列表< PriceLog>我想LINQ查詢以產生一輸出即相當於表示爲下面的數據:

LogDateTime | AVG(價格)
一月2012 | 2000
2012年2月| 3000

簡單地說:我想計算一年中每個月的平均價格。
注:LogDateTime屬性的格式應爲LogDateTime.ToString("MMM yyyy")

我曾嘗試以下,但不知道它是否會產生預期的結果:

var result = from priceLog in PriceLogList 
         group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup 
         select new PriceLog { GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)}; 

回答

18

這會給你一個匿名對象的序列,包含日期字符串和兩個屬性的平均價格:

var query = from p in PriceLogList 
      group p by p.LogDateTime.ToString("MMM yyyy") into g 
      select new { 
       LogDate = g.Key, 
       AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
       AvgSilverPrice = (int)g.Average(x => x.SilverPrice) 
      }; 

如果你需要得到PriceLog對象列表:

var query = from p in PriceLogList 
      group p by p.LogDateTime.ToString("MMM yyyy") into g 
      select new PriceLog { 
       LogDateTime = DateTime.Parse(g.Key), 
       GoldPrice = (int)g.Average(x => x.GoldPrice), 
       SilverPrice = (int)g.Average(x => x.SilverPrice) 
      }; 
2
from p in PriceLog 
    group p by p.LogDateTime.ToString("MMM") into g 
    select new 
    { 
     LogDate = g.Key.ToString("MMM yyyy"), 
     GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
     SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    } 
+0

g.LogDateTime給出錯誤! – Lucifer

+0

答案已編輯。 – MuhammadHani

2

你應該嘗試一下這樣的:

var result = 
     from priceLog in PriceLogList 
     group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup 
     select new { 
      LogDateTime = dateGroup.Key, 
      AvgPrice = dateGroup.Average(priceLog => priceLog.Price) 
     }; 
1
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList(); 

我已經把它轉換成int,因爲我的價格是場int和平均法雙倍返還。我希望這將有助於