我知道有几个关于如何从列表中创建逗号分隔字符串的问题已被提出 并 得到解答。我正在寻求一些稍微不同的帮助。
我想做的是从 a 创建一个显示友好的人类可读字符串,List<string>
其内容为"A, B and C are invalid values"。字符串的语法和格式应根据列表中的项目数而改变。该列表可以包含任意数量的项目。
例如:
List<string> myString = new List<string>() { "Scooby", "Dooby", "Doo" };
// Should return "Scooby, Dooby and Doo are invalid values."
List<string> myString = new List<string>() { "Scooby", "Dooby" };
// Should return "Scooby and Dooby are invalid values."
List<string> myString = new List<string>() { "Scooby" };
// Should return "Scooby is an invalid value."
这是我到目前为止所做的:
string userMessage = "";
foreach(string invalidValue in invalidValues)
{
userMessage = " " + userMessage + invalidValue + ",";
}
// Remove the trailing comma
userMessage = userMessage.Substring(0, userMessage.LastIndexOf(','));
if (invalidValues.Count > 1)
{
int lastCommaLocation = userMessage.LastIndexOf(',');
userMessage = userMessage.Substring(0, lastCommaLocation) + " and " + userMessage.Substring(lastCommaLocation + 1) + " are invalid values.";
}
else
{
userMessage = userMessage + " is an invalid value.";
}
有没有更好或更有效的方法来做到这一点?