简体   繁体   English

在C#中将列表组合转换为逗号分隔的字符串

[英]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 输出: D410D430D440D420代替D410,D430,D440,D420

What is the most simple way to convert the List<string> into a comma-separated string? List<string>转换为逗号分隔的字符串的最简单方法是什么?

EDIT #01 编辑#01

Your suggestion working, but I need this new output : 您的建议有效,但是我需要这个新输出:

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

Because use this string on sql query. 因为在sql查询中使用此string

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 或尝试基于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' 您需要这样输出=> '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) 输出:(来自调试器)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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