如何使用Linq聚合使用单引号 [英] How to use Linq aggregate with single quotes
问题描述
让我们假设我有一个字符串集合,像这样:
Let's assume that I have a collection of strings, like so:
IList<string> myList = new List<string>(){"one", "two", "three"};
使用myList.Aggregate
我想最后加上'一个",两个",三个"(包括单引号)
Using myList.Aggregate
I would like to end up with "'one', 'two', 'three'" (including single quotes)
有人仅使用Aggregate函数就能做到这一点吗?我在想些什么
Does someone have a sleak way of doing this, only using the Aggregate function? I was thinking something in the lines of
myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));
但这只是解决方案的一半.
but that's only half the solution.
推荐答案
是否有理由使用Aggregate
而不是更简单的string.Join
?
Any reason to use Aggregate
rather than the simpler string.Join
?
string joined = string.Join(", ", myCollection.Select(x => "'" + x + "'"));
(如果使用的是.NET 3.5,则添加ToArray
调用.)
(Add a ToArray
call if you're using .NET 3.5.)
您可以使用Aggregate
(理想情况下使用StringBuilder
)实现string.Join
,但这并不令人愉快.假设一个非空集合,我认为应该这样做:
You can implement string.Join
using Aggregate
(ideally using a StringBuilder
) but it's not terribly pleasant. Assuming a non-empty collection, I think this should do it:
string csv = myCollection.Aggregate(new StringBuilder("'"),
(sb, x) => sb.AppendFormat("{0}', '"),
sb => { sb.Length -= 3;
return sb.ToString(); });
这篇关于如何使用Linq聚合使用单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!