1

I have a collection in C# like this:

Collection<double> temp = new Collection<double>();

and I need to calculate the maximum, minimum and average value in the collection from a certain index to the end of the collection. For example, from the 10th item to the last item in the collection.

I use temp.Max();, temp.Min(); and temp.Average(); to calculate those values in the entire collection but I don't know how to do that for certain values in the collection.

Many thanks for your help!

betelgeuse
  • 430
  • 2
  • 10
  • 24
  • 2
    So your question is not _"How to calculate ..."_, but _"How to get a subset of a collection"_, which is answered in [Enumerate through a subset of a Collection in C#?](http://stackoverflow.com/questions/884732/enumerate-through-a-subset-of-a-collection-in-c). – CodeCaster Feb 24 '14 at 13:37
  • @CodeCaster: Or you could look at it as the question being "how to calculate" and the answer being "by getting the subset you want to calculate over". – Chris Feb 24 '14 at 13:40
  • @Chris I disagree, OP knows how to calculate for the entire collection, so the calculation part is irrelevant. – CodeCaster Feb 24 '14 at 13:41
  • 1
    Yes, if he knows how to get a subset he can get a solution but that assumes he knows that getting a subset is the best way to do this. There may have been the option to pass a filter into the methods being used or something. Implying that the OP should have asked a different question is suggesting levels of knowledge that he didn't necessarily have. – Chris Feb 24 '14 at 13:43
  • 1
    Thanks for your comments. Of course, the only thing I need is how to get a subset of a collection, the other part I new. I change the title of the question. Thanks for your help. – betelgeuse Feb 24 '14 at 13:53

2 Answers2

4

Just skip the number of items and then apply the aggregation functions like below!

var startIndex = 10; // zero-based, say
var max = temp.Skip(startIndex).Max();
var min = temp.Skip(startIndex).Min();
var avg = temp.Skip(startIndex).Average();
Wasif Hossain
  • 3,900
  • 1
  • 18
  • 20
3

Say you want to calculate the average of the value from index 3 onwards

values.Skip(3).Average();

Say you want to calculate the average of the value between index 3 and 7 (inclusive)

values.Skip(3).Take(5).Average();
dcastro
  • 66,540
  • 21
  • 145
  • 155