I am trying to pass an Array to a method and then return a string I can use for a SQL WHERE clause. I have the following and it works just fine. But is there a better way? I am looking for one of the two results;
WHERE (ColumnName IN (12, 34, 56, 78, 90))WHERE (ColumnName IN ('12', '34', '56', '78', '90'))
public static string setInSearchFilter(string psSearchFilter, string psColumnName,
string[] paObjectValues, bool pbIsString)
{
string lsDelimiter = "'", lsRetVal = string.Empty, lsObjectValues = string.Empty;
if (!pbIsString)
{
lsDelimiter = string.Empty;
}
if (!string.IsNullOrEmpty(psSearchFilter))
{
lsRetVal = psSearchFilter + " AND ";
}
for (int i = 0; i <= paObjectValues.GetUpperBound(0); i++)
{
lsObjectValues += lsDelimiter + paObjectValues[i] + lsDelimiter;
if (i < paObjectValues.GetUpperBound(0))
{
lsObjectValues += ", ";
}
}
return lsRetVal += "(" + psColumnName + " IN (" + lsObjectValues + "))";
}
As suggested in the comments,
string.Join:This assumes there’s something in the list, so make sure to throw or return if the filter set is empty.
You might also consider doing some kind of validation on the items to prevent SQL injection: