gpt4 book ai didi

c# - 如何使用Linq聚合使用单引号

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

假设我有一个字符串集合,如下所示:

IList<string> myList = new List<string>(){"one", "two", "three"};


我想使用 myList.Aggregate结尾为“'一个”,“两个”,“三个”(包括单引号)

有人仅使用Aggregate函数就能做到这一点吗?我在想些什么

myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));


但这只是解决方案的一半。

最佳答案

有什么理由使用Aggregate而不是更简单的string.Join吗?

string joined = string.Join(", ", myCollection.Select(x => "'" + x + "'"));


(如果使用的是.NET 3.5,请添加 ToArray调用。)

您可以使用 string.Join(最好使用 Aggregate)实现 StringBuilder,但这并不令人愉快。假设一个非空集合,我认为应该这样做:

string csv = myCollection.Aggregate(new StringBuilder("'"),
(sb, x) => sb.AppendFormat("{0}', '"),
sb => { sb.Length -= 3;
return sb.ToString(); });

关于c# - 如何使用Linq聚合使用单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8095480/

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