我如何用c#优雅地做到这一点?
例如,一个数字可以是1到100之间。
我知道一个简单的if (x >= 1 && x <= 100)就足够了;但是有很多语法糖和新特性不断添加到c# /。Net这个问题是关于更习惯的(一个可以称之为优雅的)写法。
性能不是问题,但请在非O(1)的解决方案中添加性能说明,因为人们可能会复制粘贴建议。
我如何用c#优雅地做到这一点?
例如,一个数字可以是1到100之间。
我知道一个简单的if (x >= 1 && x <= 100)就足够了;但是有很多语法糖和新特性不断添加到c# /。Net这个问题是关于更习惯的(一个可以称之为优雅的)写法。
性能不是问题,但请在非O(1)的解决方案中添加性能说明,因为人们可能会复制粘贴建议。
当前回答
好吧,我会配合的。已经有这么多答案了,但也许还有一些其他新奇的空间:
(显然你根本不用这些)
var num = 7;
const int min = 5;
const int max = 10;
var inRange = Math.Clamp(num, min, max) == num;
Or
var num = 7;
const int min = 5;
const int max = 10;
var inRange = num switch { < min => false, > max => false, _ => true };
Or
var num = 7;
const int min = 5;
const int max = 10;
var inRange = num is >= min and <= max;
好吧,也许你可以用最后一个。
好的,再来一个
var num = 7;
const int min = 5;
const int max = 10;
var inRange = Enumerable.Range(min, max-min).Contains(num);
其他回答
我不知道,但我用这个方法:
public static Boolean isInRange(this Decimal dec, Decimal min, Decimal max, bool includesMin = true, bool includesMax = true ) {
return (includesMin ? (dec >= min) : (dec > min)) && (includesMax ? (dec <= max) : (dec < max));
}
这是我使用它的方式:
[TestMethod]
public void IsIntoTheRange()
{
decimal dec = 54;
Boolean result = false;
result = dec.isInRange(50, 60); //result = True
Assert.IsTrue(result);
result = dec.isInRange(55, 60); //result = False
Assert.IsFalse(result);
result = dec.isInRange(54, 60); //result = True
Assert.IsTrue(result);
result = dec.isInRange(54, 60, false); //result = False
Assert.IsFalse(result);
result = dec.isInRange(32, 54, false, false);//result = False
Assert.IsFalse(result);
result = dec.isInRange(32, 54, false);//result = True
Assert.IsTrue(result);
}
In production code I would simply write 1 <= x && x <= 100 This is easy to understand and very readable. Starting with C#9.0 we can write x is >= 1 and <= 100 Note that we must write x only once. is introduces a pattern matching expression where and is part of the pattern. && would require us to repeat x is as in x is >= 1 && x is <= 100 Here is a clever method that reduces the number of comparisons from two to one by using some math. There is not necessarily a performance advantage in doing so, but it is elegant. The idea is that one of the two factors becomes negative if the number lies outside of the range and zero if the number is equal to one of the bounds: If the bounds are inclusive: (x - 1) * (100 - x) >= 0 or (x - min) * (max - x) >= 0 If the bounds are exclusive: (x - 1) * (100 - x) > 0 or (x - min) * (max - x) > 0
static class ExtensionMethods
{
internal static bool IsBetween(this double number,double bound1, double bound2)
{
return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
}
internal static bool IsBetween(this int number, double bound1, double bound2)
{
return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
}
}
使用
double numberToBeChecked = 7;
var result = numberToBeChecked.IsBetween(100,122);
var result = 5.IsBetween(100,120);
var result = 8.0.IsBetween(1.2,9.6);
有很多选择:
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'"
就像其他人说的,使用简单的if。
你应该考虑一下顺序。
e.g
1 <= x && x <= 100
容易读吗
x >= 1 && x <= 100