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

后端 未结 8 2151
猫巷女王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 20:54

    class Range
    {
       public int Start { get; set; }
       public int End { get; set; }
    
       static Dictionary values;
       static int[] arrToBinarySearchIn;
       public static void BuildRanges(IEnumerable ranges) { 
            values = new Dictionary();
            foreach (var item in ranges)
                values[item.Start] = item;
            arrToBinarySearchIn = values.Keys.ToArray();
            Array.Sort(arrToBinarySearchIn);
       }
       public static Range GetRange(int value)
       {
           int searchIndex = Array.BinarySearch(arrToBinarySearchIn, value);
           if (searchIndex < 0)
               searchIndex = ~searchIndex - 1;
           if (searchIndex < 0)
               return null;
           Range proposedRange = values[arrToBinarySearchIn[searchIndex]];
           if (proposedRange.End >= value)
               return proposedRange;
           return null;
       }
    }
    

提交回复
热议问题