I have the following class structure :
public class PriceLog
{
public DateTime LogDateTime {get; set;}
public int Price {get; set;}
}
For a List< PriceLog > I want a Linq query to generate an output which is equivalent to the data represented as below:
LogDateTime | AVG(Price)
Jan 2012 | 2000
Feb 2012 | 3000
Simply : I want to compute the average price over each month of the year.
Note: LogDateTime property should be formatted as LogDateTime.ToString("MMM yyyy")
I have tried the following, but not sure whether it will generate the desired result:
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)};
This will give you sequence of anonymous objects, containing date string and two properties with average price:
If you need to get list of PriceLog objects: