C#中foreach的代码优化

Ven*_*kat 1 c#

码:

string testquestions = "1,2,100,3,4,101,98,99";
string[] qidarray = testquestions.Split(',');

StringBuilder sb = new StringBuilder();

foreach (string s in qidarray)
{
    sb.Append(String.Format(@"({0}),",s));
}

string output= sb.ToString().Substring(0, sb.ToString().Length - 1);
Run Code Online (Sandbox Code Playgroud)

期望的输出=

(1),(2),(100),(3),(4),(101),(98),(99)
Run Code Online (Sandbox Code Playgroud)

代码有效.我想知道这是实现结果的最佳方式.有没有更好的方法来达到预期的效果?

有没有办法不使用foreach循环?

use*_*994 8

这样就可以了.代码首先拆分字符串并使用linq格式化为所需的输出.

var strToPrint = string.Join(",", testquestions.Split(',')
                       .Select(s => string.Format(@"({0})", s)));
Run Code Online (Sandbox Code Playgroud)

控制台输出

Console.WriteLine(string.Join(",", testquestions.Split(',')
                        .Select(s => string.Format(@"({0})", s))));
Run Code Online (Sandbox Code Playgroud)

您可以在这里查看实时小提琴 - https://dotnetfiddle.net/4zBqMf

编辑:

正如@paparazzo所建议的那样,您可以使用字符串插值将语法编写为

var strToPrint = string.Join(",", testquestions.Split(',').Select(s => $"({s})"));
Run Code Online (Sandbox Code Playgroud)

现场小提琴 - https://dotnetfiddle.net/xppLH2

  • $"({s})"可能更清晰. (6认同)
  • @ user1672994你应该使用实名:`"string interpolation"`而不是"string format short notation" (2认同)