您好,我想從C#語句中刪除最後一個單詞。這是我的查詢:字符串末尾的修飾字符串
"SELECT * FROM People WHERE City = @City AND County = @County AND"
我想刪除最後一個AND編程,我該怎麼做? 感謝
您好,我想從C#語句中刪除最後一個單詞。這是我的查詢:字符串末尾的修飾字符串
"SELECT * FROM People WHERE City = @City AND County = @County AND"
我想刪除最後一個AND編程,我該怎麼做? 感謝
var query = "SELECT * FROM People WHERE City = @City AND County = @County AND";
var scrubbed = query.Substring(0, query.Length - 4);
如果最後一句話總是將是 「AND」:
if (yourString.EndsWith(" AND"))
yourString = yourString.Remove(yourString.Length - 4);
或者,如果您需要截斷一切超出了最終的空間:
int index = yourString.LastIndexOf(' ');
if (index > -1)
yourString = yourString.Remove(index);
(雖然,as Donnie says ,真正正確的答案是不要將多餘的最後一個單詞添加到字符串中。)
string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
Console.WriteLine(myString.Substring(0, myString.LastIndexOf(' ')));
但是,您也可以考慮在沒有最後一個AND的情況下構建AND子句。
List<string> andConditions = new List<string>();
andConditions.Add("City = @City");
andConditions.Add("County = @County");
string myString = "SELECT * FROM People WHERE " + string.Join(" AND ", andConditions);
多種方法用於固定已經給該字符串。
這看起來像動態生成的SQL,因此,在我看來,更合理的解決方案是永遠不會有最終的AND
那裏。這可以通過計算您添加到where
子句的參數數量和的and
之前的每個參數。
也可以通過
//............
string query = SELECT * FROM People WHERE City = @City AND County = @County AND";
char[] charsAND = { 'A', 'N', 'D'};
char[] charsOR = { 'O', 'R'};
query = query.Trim().TrimEnd(charsAND).TrimEnd(charsOR);
//
做另一種方式:
string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
myString = myString.TrimEnd(" AND".ToCharArray());
+1,打我給它 – 2010-11-19 15:54:50
+1,什麼的 「_removing_」 最後 '與' 一個巧妙的方法...我總是在循環中添加它('myString + = condition +「AND」;'),然後在我的循環之外添加一個Trim以去除脂肪,但這樣更好! :) – 2010-11-19 16:00:48
@myermian,如果你可能有0個條件,你還可以在'if(addConditions.Count> 0){...}'中加入'「WHERE」'' – 2010-11-19 18:02:57