First you query will fail in SQL Server, it should be written like:
SELECT * FROM tableA WHERE id IN (WhereClause)
What I would suggest is to use the following method to generate your whereclause:
public static string ToIntCSV(this IEnumerable<int> ints)
{
if (ints == null) throw new ArgumentNullException("ints");
string result = string.Empty;
foreach(int i in ints)
{
if (string.IsNullOrEmpty) result = i.ToString();
else result += string.Format(",{0}",i);
}
return result;
}
You could potentially use a StringBuilder
if you expect large quantities of integers.
Alternatively you could use the LINQ Aggregate()
extension too.
public static string ToIntCSV(this IEnumerable<int> ints)
{
if (ints == null) throw new ArgumentNullException("ints");
return ints.Aggregate((csvSoFar, next) => string.Format("{0},{1}",csvSoFar,next);
}
This also ensures you actually have a list of integers for your where clause.
Finally to build your query, you should get into the habit of using string.Format()
:
public void GetQuery(IEnumerable<int> ints)
{
try
{
var query = string.Format("SELECT * FROM [tableA] WHERE [ID] IN ({0})",ints.toIntCSV());
//perform sql command
}
catch (ArgumentNullException)
{
MessageBox.Show("Invalid input");
}
}
Note, unfortunately you cannot use a parameterized query in this instance, but be sure to use them elsewhere.