I have a set of first names that I need to concatenate into a comma separated string.
The generated string must adhere to the correct grammar.
If the collection contains one name, then the output should be only that name:
John
If the collection contains two names, then the output should be separated by the word "and":
John and Mary
If the collection contains three or more names, then the output must be separated by a comma, and the last name must have the word "and" in front of it:
John, Mary, and Jane
Here is the code I came up with. This is not very elegant, and I would like to know if there is a better way to do this in C # (4.0 is fine).
List<string> firstNames = new List<string>(); firstNames.Add("John"); firstNames.Add("Mary"); firstNames.Add("Jane"); string names = string.Empty; for (int i = 0; i < firstNames.Count; i++) { if (i == 1 && firstNames.Count == 2) { names += " and "; } else if (firstNames.Count > 2 && i > 0 && i != firstNames.Count - 1) { names += ", "; } else if (i != 0 && i == firstNames.Count - 1) { names += ", and "; } names += firstNames[i]; }
source share