How to elegantly check if a number is within a range?

后端 未结 27 2211
挽巷
挽巷 2020-11-27 11:17

How can I do this elegantly with C# and .NET 3.5/4?

For example, a number can be between 1 and 100.

I know a simple if would suffice; but the keyword to this

27条回答
  •  悲&欢浪女
    2020-11-27 12:04

    EDIT: New Answer provided. I was just starting out using C# when I wrote the first answer to this question, and in hindsight I now realize that my "solution" was / is naive and inefficient.

    My original answer: I'd go with the more simple version:

    if(Enumerable.Range(1,100).Contains(intInQuestion)) { ...DoStuff; }

    A Better Way

    As I haven't seen any other solution that is more efficient (according to my tests at least), I'll give it another go.

    New and better way that also works with negative ranges:

    // 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);
    
    

    This can be used with both positive and negative ranges and defaults to a range of

    1..100 (inclusive) and uses x as the number to check followed by an optional range defined by min and max.

    Adding Examples For Good Measure

    Example 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));
    
    

    Returns:

    True
    True
    True
    False
    True
    

    Example 2: Using a list of random ints between 1 and 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();
    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);
    

    Returns:

    66660 ints found in range 1..100
    
    

    Execution Time: 0.016 second(s)

提交回复
热议问题