2013-03-22 39 views
6

我有一個值列表,例如:G1,G2,G2.5,G3,G4等。)我如何檢查c#中這些值的範圍,如果if我想看看G1和G2.5之間的價值是什麼?檢查包含數字的字符串值的範圍

在Vb.net我可以這樣做:

 Select Case selectedValue 
      Case "G1" To "G2.5" //This would be true for G1, G2, and G2.5 

我怎麼能做到這在C#?

回答

4
  1. selectedValue中刪除
  2. 將剩餘的解析爲decimal
  3. 對十進制值

實現邏輯 -

var number = decimal.Parse(selectedValue.Replace("G", "")); 
if (number >= 1.0m && number <= 2.5m) 
{ 
    // logic here 
} 
+0

謝謝,我認爲任何這些答案都可以工作,但是你的代碼是最少的。欣賞它。 – TMan 2013-03-22 17:01:12

+0

這不僅僅是更少的代碼 - 它也更加優雅。 :) – 2013-03-22 18:27:24

2

要執行字符串比較,你可能只是這樣做

if (string.Compare(selectedValue, "G1") >= 0 && string.Compare(selectedValue, "G2.5") <= 0) 
{ 
    ... 
} 

但是做數字比較,你必須分析它爲數字(doubledecimal

var selectedValueWithoutG = selectedValue.Substring(1); 
var number = decimal.Parse(selectedValueWithoutG); 
if (number >= 1D && number <= 2.5D) 
{ 
    ... 
} 
2

首先,你需要分析你的價值:

var number = decimal.Parse(selectedValue.Substring(1)) 

那麼你可以申請一個擴展方法是這樣的:

bool Between(this int value, int left, int right) 
{ 
    return value >= left && value <= right; 
} 

if(number.Between(1, 2.5)) {.....} 
相關問題