2

I m trying to average an array based on criteria in another array.

//array with a number of dates including hourly data
double[] dates;
//array with values, same length as dates and corresponding data points
double[] vals;

This is what I would like to do:

double[] dailyavgs = vals.GroupBy((v, i) => DateTime.FromOADate(dates[i]).Date()).Average().ToArray();

but this fails. Could you please point me in the right direction?

1
  • Zip these two collections together and then group and average. Commented Feb 29, 2016 at 11:41

1 Answer 1

2

You can select an anonymous type and then use GroupBy:

double[] dailyavgs = vals
    .Select((v, i) => new { Date = DateTime.FromOADate(dates[i]).Date, Value = v })
    .GroupBy(x => x.Date)
    .Select(g => g.Average(x => x.Value))
    .ToArray();

Another similar approach using Enumerable.Zip:

double[] dailyavgs = vals
    .Zip(dates, (v, d) => new { Date = DateTime.FromOADate(d).Date, Value = v })
    .GroupBy(x => x.Date)
    .Select(g => g.Average(x => x.Value))
    .ToArray();

The latter has one advantage: it doesn't throw an exception if both arrays don't have the same size: " If the input sequences do not have the same number of elements, the method combines elements until it reaches the end of one of the sequences. For example, if one sequence has three elements and the other one has four, the result sequence has only three elements"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.