Reputation: 30882
I have a LINQ in a method that is being passed an array of HalfHour
objects, each of which contains a DateAndTime
and a HalfHourNumber
.
I need to query for each of these separately, and then average the result. Currently my query only works for the first element (I'm selecting element [1]
):
internal static decimal? Average(this IQueryable<LOSSES> query, HalfHour[] array)
{
var list = query.ToList();
var numbers = (from q in list
where q.DAY == array[1].DateAndTime.Date
select q).Select(x => Calculations.SingleElement(x,
array[1].HalfHourNumber));
return numbers.Average();
}
How would I prevent needing to do this within a loop (calling the query multiple times) yet keep the objects properties associated correctly?
Upvotes: 0
Views: 97
Reputation: 437376
To get a list of averages to go with your list of LOSSES
:
var averages = list.Select(
q => array.Where(hh => q.DAY == hh.DateAndTime.Date)
.Select(hh => Calculations.SingleElement(q, hh.HalfHourNumber)
.Average()).ToList();
Or, to associate each LOSSES
with the average in a dictionary (if LOSSES
supports being used as a key):
var averages = list.ToDictionary(
q => q,
q => array.Where(hh => q.DAY == hh.DateAndTime.Date)
.Select(hh => Calculations.SingleElement(q, hh.HalfHourNumber)
.Average()
);
Upvotes: 1