我有以下类结构:
public class PriceLog
{
public DateTime LogDateTime {get; set;}
public int Price {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
对于List <PriceLog>,我希望Linq查询生成一个输出,该输出等效于如下所示的数据:
LogDateTime | AVG(价格)
2012年1月| 2000年
2月2012 | 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)};
Run Code Online (Sandbox Code Playgroud)
Ser*_*kiy 21
这将为您提供一系列匿名对象,包含日期字符串和两个平均价格的属性:
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)
};
Run Code Online (Sandbox Code Playgroud)
如果您需要获取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)
};
Run Code Online (Sandbox Code Playgroud)