I am doing something as follows..
querybuilder = ("SELECT Type, Text FROM [Element] WHERE Id IN( ");
foreach (var item in CaseIdList)
{
querybuilder += item + ",";
}
querybuilder += ")";
at the last insdie the closing bracket I am getting a comma. How to remove that.
To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!
First, you want to TRIM your data to get rid of leading and trailing spaces. Then REVERSE it and check if the first character is , . If it is, remove it, otherwise do nothing. Then REVERSE it back again.
use TrimEnd(',');
to remove last comma from the string, string.TrimEnd
After the foreach loop use:
querbuilder = querybuilder.TrimEnd(',');
Instead of concatenating string, you may use StringBuilder class.
Firstly, I'd try to avoid including the values themselves directly. Use parameters where possible - it's less simple for IN(x, y, z)
style parameters, but you can either use a table-valued parameter or simply dynamically create the parameter list (e.g. to IN(@p0, @p1, @p2)
)
Secondly, I'd avoid using string concatenation in a loop - use StringBuilder
if you really have to loop round.
Thirdly, I'd use string.Join
to avoid having to loop at all:
string commaSeparated = string.Join(", ", values);
Instead of the foreach-loop u can use the string.Join method. Take a look at this
You can use String.Join(",", item);
This means there is no ugly trimming or splitting that you have to do.
I would use String.Join:
querybuilder = "SELECT Type, Text FROM [Element] WHERE Id IN( " + String.Join(",", CaseIdList.ToArray()) + ")";
I would also look into using Parameters instead of constructing SQL with strong concatenation - string concatenation is vulnerable to SQL injection attacks, and parameters are easy to use.
How you would switch to parameters depends on how you're accessing the database, and which database engine, but a quick google search should help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With