I’ve read a blog post on extension methods. There is a method on String Aggregation but I didn’t like its implementation. A few months back, I have coded the same method. Here’s my version
public static string Aggregate<T>(this IEnumerable<T> values)
{
return Aggregate(values, ",");
}
public static string Aggregate<T>(this IEnumerable<T> values, string separator)
{
return values.Aggregate(x => x.ToString(), separator);
}
public static string Aggregate<T>(this IEnumerable<T> values, Func<T, string> toString)
{
return values.Aggregate(toString, ",");
}
public static string Aggregate<T>(this IEnumerable<T> values, Func<T, string> toString, string separator)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (toString == null)
{
throw new ArgumentNullException("toString");
}
StringBuilder buffer = new StringBuilder();
foreach (var v in values)
{
if (buffer.Length > 0)
{
buffer.Append(separator);
}
buffer.Append(toString(v));
}
return buffer.ToString();
}This version is 10 times faster and it uses less memory. The method in the post creates many temporary strings, so it consumes a lot of memory. Probably we can speed up my implementation by removing the check
if (buffer.Length > 0) { //... }and removing the separator from the start but I don’t like the idea because it will create a copy of the resulting (big) string.
Hi Peter,
Nice function!
You said that we can remove the check and remove the first separator is such exists and that there will be a problem of copying the resulting (big) string. I agree with this!
But waht do you think about such implementation?
IEnumerator enumerator = values.GetEnumerator();
if (enumerator.MoveNext())
{
buffer.Append(toString(enumerator.Current));
}
while (enumerator.MoveNext())
{
buffer.Append(separator);
buffer.Append(toString(enumerator.Current));
}
I hope you will agree that it will be nice to check for the separator and if it is null or empty to not add it each time. I’m sure you have an idea how to do it!
Regards,
Anton
[...] one of its posts there is a really good implementation of string aggregation. There Peter said Probably we can [...]
[...] one of its posts there is a really good implementation of string aggregation. There Peter said Probably we can [...]
In .Net 4 you can use:
return String.Join(separator, values.Select(v => toString(v)));