具有C#

问题描述

我在string.join中使用字符串插值有一个问题

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

如何编写字符串。加入查询,下面的代码只是我的尝试,但结果不符合预期。

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

在两种情况下,输出均应为“ 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','c'

Fiddle

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...