开发者

c# create an arbitrary length generic parameter string e.g. ?,?,?

开发者 https://www.devze.com 2022-12-24 21:47 出处:网络
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.

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.Pa开发者_运维百科rameterName).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.


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.


Along the lines of @Jon's answer:

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

精彩评论

暂无评论...
验证码 换一张
取 消