开发者

C# Using Enumerable.Range()

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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜