简体   繁体   中英

Convert List Combo into Comma-Separated String in c#

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

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'

没有foreach

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

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM