繁体   English   中英

String.Join() 对 C# 中的字符串数组进行字符串插值

[英]String.Join() with string interpolation for string array in C#

我在 string.join 中使用字符串插值时遇到问题

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

如何编写 string.Join 查询,下面的代码只是我的尝试,但结果并不如预期。

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

在这两种情况下,output 应该是 'a','b','c'

如何将 string.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'

小提琴

暂无
暂无

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

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