你可以使用string.Join() https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8 here:
var result = string.Join(", ", v.Split(",").Select(x => $"'{x}'"));
Console.WriteLine(result);
// '10', '14', '18', '21'
这基本上通过以下方式连接项目", "
,然后在每个字符串周围投影单引号Enumerable.Select() https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8来自 LINQ。
您还可以添加单引号而无需$ - 字符串插值 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated:
var result = string.Join(", ", v.Split(",").Select(x => "'" + x + "'"));
As @拉西尔·希兰 https://stackoverflow.com/questions/61115548/split-a-comma-separated-string-and-add-quotes-in-c-sharp-elegant-solution/61115643#comment108120871_61115643在评论中有用地指出,我们在这里不需要 LINQ,只需将结果括起来即可"'"
并加入"', '"
:
var result = "'" + string.Join("', '", v.Split(",")) + "'";