在C#中
通常寫比較都會用一般的運算子(operator) == 或是Equal()來處理
但這只能用於數值型別(Int、Double、Float....等等)
發現好像蠻多人對於字串(String)值的比較蠻不熟的
故這邊來補充一下用法
C#字串比較 string.CompareTo()用法
以0為基準做判斷,比較淺顯易懂
- a.CompareTo(b) > 0 表示 a > b
- a.CompareTo(b) == 0 表示 a = b
- a.CompareTo(b) < 0 表示 a < b
- a.CompareTo(b) >=0 表示 a >= b
- a.CompareTo(b) <=0 表示 a <= b
string.CompareTo()觀念
- 輸出:只會有 -1, 0, 1 三種結果
通常用於:
- 一般兩個字串做比較
- 串接Linq的Where或是Join條件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Exaple.1 | |
string a = "10"; | |
string b = "20"; | |
Console.log(a.CompareTo(b)); | |
//輸出-1,因為a < b | |
//Exaple.2 | |
string a = "10"; | |
string b = "10"; | |
Console.log(a.CompareTo(b)); | |
//輸出0,因為a = b | |
//Exaple.3 | |
string a = "20"; | |
string b = "10"; | |
Console.log(a.CompareTo(b)); | |
//輸出1,因為a > b |
【口訣:前面跟後面比較,大於就是1,等於就是0,小於就是-1】
實際應用
在LinQ的Where中,我們可以利用CompareTo做字串的比較
我們以一個SQL語法為例「抓出Table中欄位A小於等於欄位B的所有資料」
SQL語法:
Select * from Table Where ColumnA <= ColumnB
我們以一個SQL語法為例「抓出Table中欄位A小於等於欄位B的所有資料」
SQL語法:
Select * from Table Where ColumnA <= ColumnB
明明SQL中有Convert可以用,為什麼不轉型後再比較呢?
在SQL語法中,可以直接使用字串做比較,但如果透過轉型來做比較會發生什麼事情?
加上Convert後:
Select * from Table where Convert(int, ColumnA) <= Convert(int, ColumnB)
Select * from Table where Convert(int, ColumnA) <= Convert(int, ColumnB)
這樣寫會發生什麼事情?
在Select之前,資料庫會把欄位A與欄位B都先轉型為Int之後再做比較
這個Table中
如果有100筆資料,就會轉型100次
如果有100筆資料,就會轉型100次
如果有1000比資料,就會轉型1000次
以此類推,資料庫的效能一定會被拖慢
Linq使用CompareTo方法
所以我們需要用到這個方法,在Linq to SQL中使用CompareTo方法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//使用Linq to SQL來示範string.CompareTo用法 | |
//以下使用C#的Lambda寫法來表示 | |
var query = dbcontext.database.Table.GetAll().Where(x => x.ColumnA.CompareTo(x.ColumnB) <= 0); | |
//意即 select * from Table where ColumnA <= ColumnB |
後記
知道有人寫好幾年C#還是不太懂怎麼用CompareTo,令十億人都驚呆了阿阿阿阿阿阿阿....
小聲說,其實我自己也是剛會用沒幾個月(被打飛
感謝各位收看~
To Be Continued.