我有一个名字集合,我需要将它们组合成逗号分隔的字符串.
生成的字符串需要遵循正确的语法.
John
John and Mary
如果集合包含三个或更多名称,则输出应以逗号分隔,并且姓氏应在其前面包含单词“and”:
John,Mary,and Jane
这是我想出的代码.它不是很优雅,我想知道在C#中是否有更好的方法来实现这一点(4.0可以).
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]; }
解决方法
我认为它不会比以下更优雅:
if (names.Count == 0) return ""; if (names.Count == 1) return names[0]; if (names.Count == 2) return names[0] + " and " + names[1]; return String.Join(",",names.Take(names.Count - 1)) + ",and " + names[names.Count - 1];
我没有编译这个,但我认为你明白了.
编辑:更短,但可读性更低:
if (names.Count <= 2) return String.Join(" and ",names); return String.Join(",names.Take(names.Count - 1)) + ",and " + names[names.Count - 1];