How would I search a range of ranged values using C#

后端 未结 8 2163
猫巷女王i
猫巷女王i 2021-02-10 20:49

I have a list of values like this

1000, 20400
22200, 24444

The ranges don\'t overlap.

What I want to do is have a c# function that can

8条回答
  •  伪装坚强ぢ
    2021-02-10 21:13

    class Ranges
    {
        int[] starts = new[] { 1000, 22200 };
        int[] ends = new[] { 20400, 24444 };
    
        public int RangeIndex(int test)
        {
            int index = -1;
    
            if (test >= starts[0] && test <= ends[ends.Length - 1])
            {
                index = Array.BinarySearch(ends, test);
    
                if (index <= 0)
                {
                    index = ~index;
                    if (starts[index] > test) index = -1;
                }
            }
    
            return index;
        }
    }
    

    Obviously, how you instantiate the class is up to you. Maybe pass in a DataTable and construct the arrays from that.

提交回复
热议问题