簡體   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