Hi,

I need some help to count the number of values between some range.

``````var listSource = new List<double>();

//number of classes -> in this case will be 3
int nClasses = Convert.ToInt16(Math.Round(Math.Sqrt(listSource.Count)));

//retrieve max and min values
double minValue = listSource.Min();
double maxValue = listSource.Max();

//calculation of step interval
double step = (maxValue - minValue) / nClasses;

//this list contains the limits of the classes
List<double> list_steps = new List<double>();

for (int i = 0; i < nClasses; i++) {
}

//now start my problem
``````

At this moment I have:

• list with values (10,15,22,30,35,40,42,45)
• list with ranges (10, 21.6 , 33.33 , 45)

I want to retrieve a list containg the count:

values between 10 and 21.6 -> 2
values between 21.6 and 33.33 -> 2
values between 33.33 and 45 -> 4

But all this listSource and list of ranges are dynamic, i cannot input a condition like if....

Any ideas :(

## All 5 Replies

Not too difficult

``````int[] counts = new int[list_steps.Length - 1];
for (int i = 0; i < list_steps.Length -1; i++) {
counts[i] = listSource.Select(p => p >= list_steps[i] && p <= list_steps[i+1]).Count();
}
``````

Thanks for your reply, but this retrieves always value 8 :(

Sorry, brain freeze. 'Length' should be 'Count' and 'Select' should be 'Where'. That will teach me to write stuff without checking :)

Thanks for your time Momerath

``````  int[] counts = new int[list_steps.Count - 1];

for (int i = 0; i < list_steps.Count - 1; i++)
{
counts[i] = listSource.Where(p => p >= list_steps[i] && p <= list_steps[i+1]).Count();

}

foreach (int nb in counts) {
Console.WriteLine(nb);
}
``````

Now it retrieves this values:

2
2
3

There is missing one in last class...
it should be

2
2
4

If i change the last value to 44 this retrieves me 2,2,4

its weird because if I change the last value to different ones, sometimes the result is ok, but another times it fails... :(

That has to do with the fact that doubles are inexact except for specific values. If you check the top value for your range checking you'll probably see that it is 44.9999... something, and not 45. To fix this you could make your ranges into this:

``````list_steps.Add(minValue);
for (int i = 0; i < nClasses-1; i++) {