我可能有绳子
select 'abc','xyz','123' Union all select 'def','wer','456' Union all字符串是由循环产生的。
foreach(var item in obj)
{
" SELECT'" + item.a + "'," + item.b + ," + item.c + "UNION ALL";
}现在,我想删除在最后一个"Union all"中编写的string.How,我可以这样做,这是单或使用C#中的正则表达式,.IndexOf无法工作,因为我的字符串中有多个"Union all"。
发布于 2019-06-20 14:07:09
据我所见,您正在尝试从几个finalQuery中构建select;您可以在Join的帮助下完成它。
string[] selects = new string[] {
"select 'abc','xyz','123'",
"select 'def','pqr','456'",
};
// select 'abc','xyz','123' Union all select 'def','pqr','456'
string finalQuery = string.Join(" Union all ", selects);但是,如果希望删除最后一个Union all,则可以使用EndsWith测试字符串。
string finalQuery = myString.EndsWith("Union all")
? myString.Substring(0, myString.Length - "Union all".Length)
: myString;编辑:如果您在一个循环中生成selects (请参阅下面的注释),您可以尝试提取将loop转换为IEnumerable<String>的方法
private IEnumerable<string> MySelects() {
foreach(var item in obj) {
// Some Logic Here...
// When you are ready to create a select just "yield return" it and keep looping
yield return $" SELECT '{item.a}', '{item.b}', '{item.c}'";
// Some Other Logic Here...
}
}然后再一次Join
string finalQuery = string.Join(" Union all ", MySelects());最后,如果您想坚持循环(无论出于什么原因),添加if
StringBuilder sb = new StringBuilder();
foreach(var item in obj) {
// if we have a query, next one should be add via "UNION ALL"
if (sb.Length > 0)
sb.Append(" UNION ALL ");
sb.Append($"SELECT '{item.a}', '{item.b}', '{item.c}'");
}
string finalQuery = sb.ToString();发布于 2019-06-20 14:06:00
您可以结合string.Join和LINQ Skip。
string input = "select 'abc','xyz','123' Union all select 'def','wer','456' Union all";
string result = string.Join(" ", input.Split(' ').Reverse().Skip(2).Reverse());发布于 2019-06-20 14:02:02
我会从这样的词开始。如果替换变得更加复杂,您可以开始使用正则表达式。
var toRemove = "Union all";
if (yourString.EndWith(toRemove ))
{
yourString = yourString.SubString(0, yourString.Length - toRemove.Length).Trim();
}从某个逻辑位置获取toRemove字符串,不要像这样在您的过程中使用它,以避免使用魔术值。
https://stackoverflow.com/questions/56687578
复制相似问题