リストからコンマ区切りの文字列を作成する方法について、いくつかの質問と 回答 がありました。少し違うことについて助けを求めています。
私がやりたいのは、「A、B、Cは無効な値です」のList<string>
ように、aから表示しやすい人間が読める文字列を作成することです。文字列の文法と形式は、リスト内の項目の数に基づいて変更する必要があります。リストには、任意の数のアイテムを含めることができます。
例えば:
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.";
}
これを行うためのより良いまたはより効率的な方法はありますか?