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)};
You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.
GroupBy() Method in C# The GroupBy() is an extension method that returns a group of elements from the given collection based on some key value. The following is our array − int[] arr = { 2, 30, 45, 60, 70 }; Now, we will use GroupBy() to group the elements smaller than 50 − arr.
Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .
In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.
This will give you sequence of anonymous objects, containing date string and two properties with average price:
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)
};
If you need to get list of PriceLog objects:
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)
};
You should try it like this:
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)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With