2016-06-28 44 views
-3

我有這段代碼從DGV中選擇一行。%「。search。」%in C#

if (row.Cells[1].Value.ToString().Equals(searchValue)) 
{ 
    row.Selected = true; 
    break; 
} 

有沒有像

%".$searchvalue."%

從SQL在C#中使用任何東西,所以它會發現貌似出入口不僅準確的呢?如果你想找出你可以使用StartsWith像下面的字符串只有entrances

+1

可能的重複[如何在Linq中執行SQL Like%?](http://stackoverflow.com/questions/835790/how-to-do-sql-like-in-linq) –

回答

0

使用string.Contains代替的Equals

if (row.Cells[1].Value.ToString().Contains(searchValue)) 
{ 
    row.Selected = true; 
    break; 
} 
+0

非常感謝Gilad! – Vvisions

1

if (row.Cells[1].Value.ToString().StartsWith(searchValue)) 
{ 
    row.Selected = true; 
    break; 
} 

如果你想找出字符串只有endings你可以使用EndsWith像下面。

if (row.Cells[1].Value.ToString().EndsWith(searchValue)) 
{ 
    row.Selected = true; 
    break; 
} 

可以在上述情況下使用contains如果你不是那麼擔心性能。

+0

StartsWith將僅查找第一個單詞的第一個字符或將查找任何單詞的第一個字符? 如果我使用包含什麼性能影響? – Vvisions

+0

它只查找第一個單詞的第一個字符。 'Contains'使用不同的算法,它需要計算比'StartsWith'或'EndsWith'更多的組合。因此它用於我們不知道我們所需的字符串匹配器在哪裏的情況。如果你確定你需要搜索什麼,並且它在開始或結束時出現,那麼你可以使用這些。否則'Contains'不是一個不錯的選擇。 – Venky

+0

如果你想檢查每個單詞的第一個字符,那麼你需要用'space'分割字符串,並循環遍歷每一個單詞以檢查它是否以'匹配字符串'開頭。 – Venky

0

一般情況下,如果你想模仿 SQL LIKE建設可以嘗試正則表達式

public static bool Like(String value, String like) { 
    if (String.IsNullOrEmpty(like) || String.IsNullOrEmpty(value)) 
    return false; // or throw exception 

    String pattern = "^" + Regex.Escape(like).Replace("%", ".*").Replace("_", ".") + "$"; 

    return Regex.IsMatch(value, pattern); 
} 

....

String source = "abcdef"; 
// true 
bool result = Like(source, "%b_d%"); 

你的情況

if (Like(row.Cells[1].Value.ToString(), searchValue)) { ... }