我如何用c#优雅地做到这一点?

例如,一个数字可以是1到100之间。

我知道一个简单的if (x >= 1 && x <= 100)就足够了;但是有很多语法糖和新特性不断添加到c# /。Net这个问题是关于更习惯的(一个可以称之为优雅的)写法。

性能不是问题,但请在非O(1)的解决方案中添加性能说明,因为人们可能会复制粘贴建议。


当前回答

2022年6月

int id = 10;
if(Enumerable.Range(1, 100).Select(x => x == id).Any()) // true

其他回答

编辑:提供了新的答案。 当我写这个问题的第一个答案时,我刚刚开始使用c#,事后我意识到我的“解决方案”是幼稚和低效的。

我最初的回答是: 我会选择更简单的版本:

' if(Enumerable.Range(1100).Contains(intInQuestion)){…DoStuff;} '

更好的方法

因为我还没有看到任何其他更有效的解决方案(至少根据我的测试),我将再试一次。

新的和更好的方法,也适用于负范围:

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

这可以用于正负范围,并且默认为

1 . . 100(包括)并使用x作为数字来检查,然后是由min和max定义的可选范围。

为好的措施添加例子

示例1:

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

Console.WriteLine(inRange(25));
Console.WriteLine(inRange(1));
Console.WriteLine(inRange(100));
Console.WriteLine(inRange(25, 30, 150));
Console.WriteLine(inRange(-25, -50, 0));

返回:

True
True
True
False
True

示例2: 使用100000个1到150之间的随机整数的列表

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

// Generate 100000 ints between 1 and 150
var intsToCheck = new List<int>();
var randGen = new Random();
for(int i = 0; i < 100000; ++i){
    intsToCheck.Add(randGen.Next(150) + 1);
}

var counter = 0;
foreach(int n in intsToCheck) {
    if(inRange(n)) ++counter;
}

Console.WriteLine("{0} ints found in range 1..100", counter);

返回:

66660 ints found in range 1..100

Execution Time: 0.016 second(s)

如果这是偶然的,你只需要一个简单的If。如果这种情况在很多地方都发生,你可能会考虑这两个:

PostSharp。在方法编译后,用“注入”代码的属性来装饰方法。我不确定,但我可以想象它可以用来做这个。

喜欢的东西:

[Between("parameter", 0, 100)]
public void Foo(int parameter)
{
}

代码合同。优点是可以在编译时通过对代码和使用代码的地方进行静态验证来检查约束。

有很多选择:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))  //true

实际上,基本的,如果更优雅的话,可以在第一张支票中用倒序写:

if (1 <= x && x <= 100)   //true

此外,查看这篇SO帖子的正则表达式选项。

注:

LINQ solution is strictly for style points - since Contains iterates over all items its complexity is O(range_size) and not O(1) normally expected from a range check. More generic version for other ranges (notice that second argument is count, not end): if (Enumerable.Range(start, end - start + 1).Contains(x) There is temptation to write if solution without && like 1 <= x <= 100 - that look really elegant, but in C# leads to a syntax error "Operator '<=' cannot be applied to operands of type 'bool' and 'int'"

我使用下一个“优雅”的解决方案:

using static System.Linq.Enumerable;

int x = 30;
if (Range(1,100).Contains(x))  //true

来自微软文档

using static指令适用于任何具有静态成员(或嵌套类型)的类型,即使它也具有实例成员。但是,实例成员只能通过类型实例调用。

你可以访问一个类型的静态成员,而不需要用类型名限定访问:

但这对许多人来说并不简单,因为Enumerable。Range有第一个参数start和第二个参数count。 所以这种检查可能在特定情况下有用,比如当你使用Enumerable时。范围的foreach循环,在开始之前,您想知道,如果循环将执行。

例如:

        int count = 100;
        int x = 30;

        if (!Range(1, count).Contains(x)) {
            Console.WriteLine("Do nothing!");
            return;
        }

        foreach (var i in Range(1, count)) {
            // Some job here
        }

在c#中,关于速度和代码原的最佳解决方案,只有一次比较,没有约束检查,并且不会因溢出而容易出错:

public static bool IsInRange(int value, int min, int max) => (uint)(value - min) <= (uint)(max - min);

最小值和最大值包括在内。