gpt4 book ai didi

c# - C#中foreach的代码优化

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:18 25 4
gpt4 key购买 nike

代码:

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);

期望的输出=

(1),(2),(100),(3),(4),(101),(98),(99)

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

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

最佳答案

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

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

控制台输出

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

您可以在此处查看实时 fiddle - https://dotnetfiddle.net/4zBqMf

编辑:

根据@paparazzo 的建议,您可以使用字符串插值将语法编写为

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

现场 fiddle - https://dotnetfiddle.net/xppLH2

关于c# - C#中foreach的代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com