String.Join(),用于C#中的字符串数组的字符串插值



我在字符串中使用字符串插值时遇到问题。加入

string type1 = "a,b,c";
string[] type2 = new string[3] { "a", "b", "c" };

如何编写字符串。联接查询,下面的代码只是我的尝试,但结果并不像预期的那样。

string result = string.Join(",", $"'{type1}'");

在这两种情况下,输出都应该是"a"、"b"、"c">

如何使用字符串。Join((,用于字符串数组的字符串插值

如果您想在每个元素周围添加单引号,可以应用一个简单的.Select()序列,例如:

var type1 = "a,b,c";
var type2 = new string[3] { "a", "b", "c" };
// using System.Linq;
var result1 = string.Join(',', type1.Split(',').Select(x => $"'{x}'"));
var result2 = string.Join(',', type2.Select(x => $"'{x}'"));
Console.WriteLine($"Type1 : {result1}");
Console.WriteLine($"Type2 : {result2}");

该输出:

Type1 : 'a','b','c'
Type2 : 'a','b','c'

Fiddle

最新更新