2

リストからコンマ区切りの文字列を作成する方法について、いくつかの質問 回答 がありました。少し違うことについて助けを求めています。

私がやりたいのは、「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.";
}

これを行うためのより良いまたはより効率的な方法はありますか?

4

2 に答える 2

8
public static string FormatList(List<string> invalidItems)
{
    if(invalidItems.Count == 0) return string.Empty;
    else if(invalidItems.Count == 1) return string.Format("{0} is an invalid value", invalidItems[0]);
    else return string.Format("{0} and {1} are invalid values", string.Join(", ", invalidItems.Take(invalidItems.Count - 1)), invalidItems.Last());
}
于 2012-09-25T19:21:02.847 に答える