Pergunta

Am I using this is the correct manner? As far as I understand it, the following check should be false:

 int myVal = 37;
 if (Enumerable.Range(0, 10).Contains(myVal))
    // Do something
 else if (Enumerable.Range(11, 33).Contains(myVal))
    // Do somethiong else

But I seem to be getting some cases where //Do somethiong else is executed. Can I not use Enumerable.Range is this way?

Foi útil?

Solução

The signature for Enumerable.Range provides a clue:

public static IEnumerable<int> Range(
    int start,
    int count
)

The first parameter is called start; the second is called count. So your second call is returning 33 values starting with 11, which will include 37.

Outras dicas

If this particular example, its inefficient to create an enumerate in this fashion simply to check that a value lies within a particular range. if (x < y) is probably better.

It will result in every value being checked, and is a little confusing, why not do:

int myVal = 37;
if (myVal >= 0 && myVal <= 10)
    // Do something
else if (myVal <= 33)
    // Do somethiong else
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top