简体   繁体   English

使用附加连接将字符串数组转换为逗号分隔的字符串

[英]Convert Array of Strings to Comma Separated String with additional concatenation

Is there any way to convert a list of strings to a comma-separated string?有没有办法将字符串列表转换为逗号分隔的字符串?

String[] data = new String[] { "test", "abc", "123" }

Convert into:转换成:

'test', 'abc', '123'

Possible solutions:可能的解决方案:

  1. Surround every string with '' and then use String.join on the list.''包围每个字符串,然后在列表中使用String.join
  2. Foreach each string in the list and do the concatenation of '' and ',' and in the end remove last ',' Foreach列表中的每个字符串并进行''','的连接,最后删除最后一个','

Is there any simple Linq (one line expression) to do both?是否有任何简单的 Linq(单行表达式)来做这两个?

Is there any simple Linq (one line expression) to do both.是否有任何简单的 Linq(单行表达式)可以做到这两点。

string.Join(",", data.Select(item => "'" + item + "'"))

Basics of Linq: Transforms are Select statements. Linq 的基础知识:转换是Select语句。 Filters are Where statements.过滤器是Where语句。

That said, there are a lot of string manipulation tools available that aren't Linq, and they're more likely to be optimized for strings, so I'd always look to them before looking to Linq.也就是说,有很多不是 Linq 的字符串操作工具可用,而且它们更有可能针对字符串进行优化,所以我总是先查看它们,然后再使用 Linq。

您可以使用聚合 linq

Array.Skip(1).Aggregate(Array[0],(a,b) => string.Format("{0},'{1}'",a,b));
String[] data = new String[]{"test","abc","123"};
var result = string.Join(",", data.Select(o => string.Concat("'",o,"'"));

You could also use the Aggregate method: Example:您还可以使用聚合方法:示例:

List<string> fruit = new List<string> {"Apple", "Orange", "Pear", "Tomato", "Banana"};
var fruitSentence = fruit.Aggregate((current, next) => $"{current},{next}");

NOTE: if you're starting with IEnumerable or similar you have to call .ToArray() at the end of the LINQ statement like this:注意:如果您从 IEnumerable 或类似名称开始,则必须在 LINQ 语句的末尾调用 .ToArray() ,如下所示:

input parameter: IEnumerable<string> feederIdList    

var feederListString = String.Join(",", feederIdList.Select(feeder => "\"" + feeder + "\"").ToArray());

In my case I needed each string to have double quotes around it for passing into an Oracle stored procedure later.在我的情况下,我需要每个字符串在其周围加上双引号,以便稍后传递到 Oracle 存储过程。

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

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