Mark McGown
Mark McGown

Reputation: 1115

How to turn array into quote and comma delimited string for sql?

I have a list I want to pass into SQL but they must be single quote and comma delimited.

So List = a b c

But I need a string = 'a','b','c'

How can I accomplish this in a concise manner?

Something like this I think but can't see within LINQ how to add to beginning and end:

String.Join(",", arr.Select(p => p.ToString()).ToArray())

Upvotes: 5

Views: 3133

Answers (4)

Enigmativity
Enigmativity

Reputation: 117175

You should also be careful if your source data contains "'" in which case you need to escape the "'". Try this:

var arr = new [] { "a'c", "b" };

var output = String.Join(",", arr.Select(p => $"'{p.Replace("'", "''")}'"));

That gives "'a''c','b'".

Upvotes: 1

AustinWBryan
AustinWBryan

Reputation: 3327

You can do this:

String.Join(",", arr.Select(p => $"'{p.ToString()}'").ToArray());

And that will put the ' on either side of p.ToString() for each element.

Upvotes: 3

Amy B
Amy B

Reputation: 110221

Use an ORM that supports the following construction:

string[] items = GetItems();
var query = db.Rows.Where(row => items.Contains(row.ColumnName));

This way, you do not open yourself to sql injection by constructing strings to hand to the database yourself.

Upvotes: 1

StaticBeagle
StaticBeagle

Reputation: 5185

Maybe something along the lines of:

String.Join(",", arr.Select(p=> "'" + p.ToString() + "'").ToArray());

// or is p already a string

String.Join(",", arr.Select(p => "'" + p + "'").ToArray());

Upvotes: 3

Related Questions