I know several questions have been asked and answered about how to create a comma delimited string from a list. I'm looking for help on something slightly different.
What I would like to do is create a display-friendly human-readable string from a List<string>
that reads like "A, B and C are invalid values". The grammar and format of the string should change based on the number of items in the list. The list could contain any number of items.
For example:
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."
Here's what I've done so far:
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.";
}
Is there a better or more efficient way to do this?