code_junkie

Doing a range lookup in C#

Nov 13th, 2011
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. public interface IRangeComparer<TRange, TValue>
  2. {
  3. /// <summary>
  4. /// Returns 0 if value is in the specified range;
  5. /// less than 0 if value is above the range;
  6. /// greater than 0 if value is below the range.
  7. /// </summary>
  8. int Compare(TRange range, TValue value);
  9. }
  10.  
  11.  
  12. /// <summary>
  13. /// See contract for Array.BinarySearch
  14. /// </summary>
  15. public static int BinarySearch<TRange, TValue>(IList<TRange> ranges,
  16. TValue value,
  17. IRangeComparer<TRange, TValue> comparer)
  18. {
  19. int min = 0;
  20. int max = ranges.Count-1;
  21.  
  22. while (min <= max)
  23. {
  24. int mid = (min + max) / 2;
  25. int comparison = comparer.Compare(ranges[mid], value);
  26. if (comparison == 0)
  27. {
  28. return mid;
  29. }
  30. if (comparison < 0)
  31. {
  32. min = mid+1;
  33. }
  34. else if (comparison > 0)
  35. {
  36. max = mid-1;
  37. }
  38. }
  39. return ~min;
  40. }
  41.  
  42. foundRange = yourList.Where(range =› range.BottomNumber ‹= searchInt && range.TopNumber ›= searchInt).FirstOrDefault();
Add Comment
Please, Sign In to add comment