0

I'm trying to create a string from the values in a list; what I am trying to achieve is the SQL syntax which is used in an update query:

UPDATE TABLE SET COLUMN1 =X WHERE COLUMN2 IN ('A','B','C')

(A,B,C are items in my list.) How can I achieve this?

I tried:

string commaSeparatedList = _list.Aggregate((a, x) => a + ", " + x);

but it creates the list without the apostrophes.

3
  • If you are building SQL that will be executed be wary of SQL Injection attacks you may be opening your self up to. For example what if a item of your list was called ') or 1=1; --. I recommend opening a new question with a higher level overview of what you are doing and asking if there is a better method to do what you want to do. Commented Dec 17, 2012 at 8:57
  • Another way of solving this in a way that is safer than building a SQL string is using Linq To Sql to build your query for you. (open a new question if you need help doing Linq to Sql) Commented Dec 17, 2012 at 9:07
  • SQL injections don't matter right now,but thanks for the advice :) Commented Dec 17, 2012 at 9:17

3 Answers 3

6

You can also use String.Join Method instead:

string commaSeparatedList = string.Join(",", _list.Select(s => "'" + s + "'"));
Sign up to request clarification or add additional context in comments.

3 Comments

join is way faster than aggregate, have to recommend this.
So what do you do when one of the members of _list contains the value ') or 1=1; --?
That's a fair point about Join, have an upvote. I just went for "minimal code change".
3

If your code gives you exactly what you want except for the apostrophes, just stick a

.Select(s => "'" + s + "'")

between _list .and .Aggregate...

Comments

0
string commaSeparatedList = "'"+_list.Aggregate((a, x) =>  a + "','" + x )+"'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.