1

My code is as below:

List<string> colorList = new List<string>();

....

sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());

....


foreach (var Combo in colorList)
{
   Response.Write(string.Join(",", Combo));
} 

Output: D410D430D440D420 instead of D410,D430,D440,D420

What is the most simple way to convert the List<string> into a comma-separated string?

EDIT #01

Your suggestion working, but I need this new output :

'D410','D430','D440','D420' 

Because use this string on sql query.

Thank you

1

3 Answers 3

7

I think this would be very handy

var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);                      
Console.WriteLine(commaSeparated);

or try solution based on Linq

Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));

The output

D410,D430,D440,D420

Edit

string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);

will give you

'D410','D430','D440','D420'
Sign up to request clarification or add additional context in comments.

Comments

4

Without a foreach:

Response.Write(string.Join(",", colorList));

1 Comment

Your suggestion working, but I need this new output : 'D410','D430','D440','D420' Because use this string on sql query. Thank you
1

You need to output like this => 'D410','D430','D440','D420'

So try below,

string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);

What we did above?

Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.

Output: (From Debugger)

enter image description here

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.