It's ok. A bit hard to follow however since you're taking steps that really aren't necessary.
It is not necessary to give the StringBuilder
a starting capacity. Just let it do its business and you do yours, it will just work.
However if you really wanted to do this, then that's not a problem. You can clean it up a bit. Rather than aggregating over the items when adding up all the lengths, just use Sum()
instead.
var totalNamesLength = items.Sum(s => s.Length);
Don't really have much of a comment on the rest of your code. I'd be careful of using ==
/!=
comparisons in a loop that goes over consecutive values, if the loop variable were to ever change in the body of the loop, you'll have a hell of a time trying to debug any problems you have with that. I'd stick to using <
(or appropriate operator) there exclusively.
for (int idx = 1; idx < loopCount; ++idx)
// ...
I'd write this differently however as this is much more readable to me and compact.
internal static string GetEnumerated(this string[] items)
{
if (items.Length > 1)
{
// place all but the last in a comma-separated string
var commaSeparated = String.Join(", ", items.Take(items.Length - 1));
// include the last item
return commaSeparated + ", and " + items.Last();
}
return items.DefaultIfEmpty("").Single();
}
Since we know we are dealing with arrays, you won't be paying for much in terms of performance in the LINQ calls. If that bothers you, it is simple to write the equivalent without using LINQ.
internal static string GetEnumerated(this string[] items)
{
if (items.Length == 0)
return "";
if (items.Length == 1)
return items[0];
var commaSeparated = String.Join(", ", items, 0, items.Length - 1);
return commaSeparated + ", and " + items[items.Length - 1];
}