views:

119

answers:

2

I know I am forgetting to remember how to do this and it is late.

I want to, in an elegant manner, build a placeholder list for a munged sql command.

Have a command with an arbitrary number of parameters, need to build ?,?,?

Did I mention that it was a wet brain fart? this is what came out:

You are welcome to make me feel like more of an idiot if you just remember me what I am forgetting. ;-)


Ok, looks like I should be calling it a night.

Both you guys confirmed what I was doing before going off the deep end.

This is my name list,

string names = string.Join(",", _command.Parameters.Cast<SQLiteParameter>().Select(p => p.ParameterName).ToArray());

And I just replaced the p.Name with '?'

string vals = string.Join(",", _command.Parameters.Cast<object>().Select(p => "?").ToArray());

But for some reason I did not approve.

Thanks.

+1  A: 

Well, this suggests itself:

string x = string.Join(",", Enumerable.Repeat("?", count).ToArray());

In .NET 4 this can be simplified slightly as string.Join has new overloads:

string x = string.Join(",", Enumerable.Repeat("?", count));

On the other hand, I'd be tempted to just do it with a loop:

StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++)
{
    builder.Append("?,");
}
builder.Length--; // Remove trailing ,
return builder.ToString();

Either way I'd put it in a separate method, so the brevity isn't likely to matter.

Jon Skeet
Yeah, the first one I look similar to what I have, then I started shaving my llama and tried to convince myself that a regex would be good. Am on the tail end of a binge and am coming up short. just want to get throught this section before calling it a night without leaving something stupid in the file. Thanks.
Sky Sanders
r.e. separate method: this is going to be only ever called one time, ever, to build a 'bulk copy' command in a simple implementation, so will probably be inline, thus the silly imperative for elegance.
Sky Sanders
@Sky: Even if it's only going to be used once, you may well still be able to improve the readability by separating it out into a new method. If it's a choice between a more easily-understood separate method or a relatively dense single statement, I'd go for the separate method.
Jon Skeet
A: 

Along the lines of @Jon's answer:

string.Join(",", _command.Parameters.Cast<object>().Select(p => "?").ToArray())
Jimmy
That is EXACTLY what I have in my code that prompted this question. Lol. too funny. Maybe that is the best way after all. I just thought it smelled.
Sky Sanders
string.Join(",", _command.Parameters.Cast<object>().Select(p => "?").ToArray());
Sky Sanders