Determine the number of items in a list that are within the limits defined in another list

Asked

Viewed 114 times

2

I have a ListBox that contains an undetermined value of values and I want to play those values to a List<> and from what I’ve researched, I’ve made it this far:

var todosValores = lstRoll.Items.OfType<object>().Select(x => x.ToString()).ToList();
List<double> listaDeNums = todosValores.Select(s => double.Parse(s)).ToList();

var lista = new List<double>();
lista.Add(somaLinha1);
lista.Add(Math.Round((somaLinha1 + valorTamanhoIntervalo), 2));

The above code plays the values of the ListBox for a List<> and then throw it to another List<> converting to double values. It turns out that now I have another List other than those containing decimal numbers.

Supposing that my listaDeNums now load the values { 1,2,3,...,9,10 } and my another list (variable lista in the code) load the values { 2.86 , 5.65 }.

These two values need to be treated as the beginning and end of an interval that will be intersected in the listaDeNums and a variable is incremented at each number that is part of the intersection.

In this specific case exemplified by me above my variable incremented at the end, should give 3 because between 2.86 and 5.65 on a list of 1 to 10 there are 3 numbers.

  • Complicated understand what you need to do? Have some minimal example to ask your question?

  • Exactly what Ramaral posted, his second code block almost met me xD

1 answer

2

If in the "other list" item 0 is the lower limit and item 1 is the upper limit, the code below builds a list with the values that are within those limits.

var lista = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var limites = new List<double>{ 2.86, 5.65 };

var ocurrencias = new List<int>();
ocurrencias = lista.Where(valor => valor >= limites[0] && valor <= limites[1]).ToList();

If you only want to know the number of items in the list that are in the range use:

var lista = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var limites = new List<double>{ 2.86, 5.65 };
var numeroDeOcurrencias = lista.Count(valor => valor >= limites[0] && valor <= limites[1]);

See on .NET Fiddle.

  • Hello Ramaral! The second line of code almost met me... The problem is that you’re considering an open interval, and I need the closed interval, because assuming my limits were 1 to 3.26 the 1 would also count in the amount of intersections... Thus, the following is happening: https://puu.sh/zPh0x/cd07103a9e.png In the second line, too, the result should also be 3, because from 3.67 to 6.34 there are 3 numbers in the list (4.5.6)

  • Check your code because the interval is closed. See that I am using >= and <=.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.