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

Chevy Mark Sunderland
  • 401
  • 2
  • 10
  • 21
  • Possible duplicate of [Using LINQ to concatenate strings](https://stackoverflow.com/questions/217805/using-linq-to-concatenate-strings) – NibblyPig Feb 21 '19 at 10:37

3 Answers3

6

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'
GoldenAge
  • 2,918
  • 5
  • 25
  • 63
4

Without a foreach:

Response.Write(string.Join(",", colorList));
Dan Dumitru
  • 5,348
  • 1
  • 33
  • 43
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

er-sho
  • 9,581
  • 2
  • 13
  • 26