在C#中进行范围查找 – 如何实现
我试图了解如何实现Jon Skeet在线程中找到的代码: 在C#中进行范围查找?
有人可以使用以下内容提供设置示例:1-10000,10001-40000,40000+
第一组在哪里分别返回值1,2,3?
我不太清楚这段代码是如何完成的。 TX。
public interface IRangeComparer { /// /// Returns 0 if value is in the specified range; /// less than 0 if value is above the range; /// greater than 0 if value is below the range. /// int Compare(TRange range, TValue value); } /// /// See contract for Array.BinarySearch /// public static int BinarySearch(IList ranges, TValue value, IRangeComparer comparer) { int min = 0; int max = ranges.Count-1; while (min <= max) { int mid = (min + max) / 2; int comparison = comparer.Compare(ranges[mid], value); if (comparison == 0) { return mid; } if (comparison 0) { max = mid-1; } } return ~min; }
你需要很好地掌握generics来理解这段代码。 这是一个function实现:
public class Range where TValue : IComparable { public TValue Min { get; set; } public TValue Max { get; set; } public Range(TValue min, TValue max) { this.Min = min; this.Max = max; } } public class RangeComparer : IRangeComparer, TValue> where TValue : IComparable { /// /// Returns 0 if value is in the specified range; /// less than 0 if value is above the range; /// greater than 0 if value is below the range. /// public int Compare(Range range, TValue value) { // Check if value is below range (less than min). if (range.Min.CompareTo(value) > 0) return 1; // Check if value is above range (greater than max) if (range.Max.CompareTo(value) < 0) return -1; // Value is within range. return 0; } } static void Main(string[] args) { var ranges = new Range[] { new Range (1, 10000), new Range (10001, 40000), new Range (40001, int.MaxValue), }; var rangeComparer = new RangeComparer (); Console.WriteLine(BinarySearch(ranges, 7, rangeComparer)); // gives 0 Console.WriteLine(BinarySearch(ranges, 10007, rangeComparer)); // gives 1 Console.WriteLine(BinarySearch(ranges, 40007, rangeComparer)); // gives 2 Console.WriteLine(BinarySearch(ranges, 1, rangeComparer)); // gives 0 Console.WriteLine(BinarySearch(ranges, 10000, rangeComparer)); // gives 0 Console.WriteLine(BinarySearch(ranges, 40000, rangeComparer)); // gives 1 Console.WriteLine(BinarySearch(ranges, 40001, rangeComparer)); // gives 2 }
别忘了:
- 范围必须按升序排列
- 范围不得重叠
-
BinarySearch
返回的索引是从零开始的
- 通过基类创建派生类的实例,无需硬编码
- 命名空间“System”中不存在类型或命名空间名称“Device”
- Visual Studio“选择资源”对话框替换
- 有没有办法指定tcpClient中使用的本地端口?
- C# – ObjectContext实例已被释放,不能再用于需要连接的操作
- EF:对象更新过程不会更改一个属性的值
- 如何从我的C#代码隐藏发送电子邮件 – 获取System.Net.Mail.SmtpFailedRecipientException
- 无法加载文件或程序集>’System.Windows,Version = 2.0.5.0
- Mvc UserControl使用HtmlHelper与HelperResult和MvcHtmlString