Here is a broken down version of my problem :
I have a method. The argument is a list of integers. I wish to create an optimised SQL query that returns a particular value on all rows where the id of that row is equal to one of the integers in the argument list. Simple, right ?
I have a feeling I have made it more difficult than it needs to be :
private List<string> ReturnValue(List<int> ids)
{
List<string> ValuesIWantToReturn = new List<string>();
StringBuilder sb = new StringBuilder("SELECT ValueIWantToReturnfrom table WHERE ");
foreach (int id in ids)
{
sb.Append( string.Format("ID = {0} OR ", id) );
}
sb.Remove(sb.Length - 3, 3); //remove trailing "OR"
sb.Append(";");
SqlDataReader reader = RunSelectQuery( sb.ToString() );
while (reader.Read())
{
ValuesIWantToReturn.Add(reader.GetString(0));
}
return ValuesIWantToReturn;
}
Any feedback on the general readability and structure of my code would be appreciated too. It’s always nice to improve 🙂
You can use the
INsyntax rather thanORIt may be more efficient to pass the list of IDs as a table valued parameter to a stored procedure, and then join that to your table, but that may be over engineering the solution – depending on how long your list of numbers is.
Instead of your loop, you can use
string.Jointo build your list(assuming that there is always at least one number in the list)