利用linq快速判断给定数字是否包含在某个段范围内

一、需求:

知道某段范围
0x0020~0x007F
0x00A0~0x017F
0x01A0~0x01CF
0x01F0~0x01FF
0x0210~0x021F
0x1EA0~0x1EFF
给定一个值,快速判断给定值是否在以上编码范围内

二、解决方案


用面向对象的方案解决

1、每个段都有一个最小值,一个最大值,定义一个类

 1 public Section(int minValue, int maxValue)
 2         {
 3             this.MinValue = minValue;
 4             this.MaxValue = maxValue;
 5         }
 6         
 7         /// <summary>
 8         /// 存储最小值
 9         /// </summary>
10         public int MinValue { get; set; }
11 
12         /// <summary>
13         /// 存储最大值
14         /// </summary>
15         public int MaxValue { get; set; }

 

2、初始化数据

 

 1   private static readonly List<Section> lstSections;
 2 
 3         static Program()
 4         {
 5             lstSections = new List<Section>
 6                               {
 7                                   new Section(0x0020, 0x007F),
 8                                   new Section(0x00A0, 0x017F),
 9                                   new Section(0x01A0, 0x01CF),
10                                   new Section(0x01F0, 0x01FF),
11                                   new Section(0x0210, 0x021F),
12                                   new Section(0x1EA0, 0x1EFF)
13                               };
14             
15         }

 

用linq比较大小验证方法

 /// <summary>
        /// Vaid
        /// </summary>
        /// <param name="value"></param>
        /// <returns>True:在这个范围 Fase:不在这个范围</returns>
        public static bool IsValidSection(int value)
        {
            var lstFind = lstSections.FindAll(p => value >= p.MinValue && value <= p.MaxValue);
            return lstFind.Count > 0;
        }

 

调用该方法:

 1  static void Main(string[] args)
 2         {
 3 
 4             
 5             while (true)
 6             {
 7                 Console.Write("请输入一个16进制数值:");
 8                 var input = Console.ReadLine();
 9                 if (input == "q")
10                 {
11                     break;
12                 }
13                 var result = 0;
14                 var b = int.TryParse(input.ToUpper(), NumberStyles.AllowHexSpecifier, null, out result);
15                 if (b)
16                 {
17                     Console.WriteLine("{0}-{1}", input, IsValidSection(result) ? "在给定范围内" : "不在给定范围内");
18                 }
19                 else
20                 {
21                     Console.WriteLine("输入值错误");
22                 }
23             }
24 
25         }

 

 

 

posted @ 2014-04-24 08:08  cnkker.com  阅读(1077)  评论(0编辑  收藏  举报