Possible Duplicate:
LINQ list to sentence format (insert commas & “and”)
Imagine these inputs and results:
[] -> ""
["Hello World!"] -> "Hello World!"
["Apples", "bananas"] -> "Apples, and bananas" (put your grammar books away)
["Lions", "Tigers", "Bears"] -> "Lions, Tigers, and Bears" (oh my!)
Now, imagine that the inputs are all of IEnumerable<string>
. What is a good (where good may encompass "small and tidy", "easy to understand", "uses the full ability of LINQ", or other as long as it's justified) to write a function in C# to do this? I would really like to avoid "imperative loop" approaches.
My current approach looks like:
string Commaize (IEnumerable<string> list) {
if (list.Count() > 1) {
list = list.Take(list.Count() - 2).Concat(
new[] { list.Reverse().Take(2).Reverse()
.Aggregate((a, b) => a + " and " + b) });
}
return String.Join(", ", list.ToArray());
}
But it just doesn't feel very "good". It's for .NET3.5 so the ToArray()
bit is required here. If list
is null the result is UB.