解決策を見つけられることはわかっていますが、もっと簡潔な解決策があるかどうか疑問に思っています。常にString.Join(", ", lList)
ありますが、結合文字列としてlList.Aggregate((a, b) => a + ", " + b);
最後のものに例外を追加したいと思います。どこかに使用できるインデックス値がありますか", and "
? Aggregate()
ありがとう。
14063 次
6 に答える
28
あなたはこれを行うことができます
string finalString = String.Join(", ", myList.ToArray(), 0, myList.Count - 1) + ", and " + myList.LastOrDefault();
于 2013-07-09T23:55:10.813 に答える
19
空のリストと単一のアイテムを含むリストで機能するソリューションを次に示します。
C#
return list.Count() > 1 ? string.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last() : list.FirstOrDefault();
VB
Return If(list.Count() > 1, String.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last(), list.FirstOrDefault())
于 2014-08-28T09:01:34.160 に答える
12
私は次の拡張メソッドを使用します (コードガードもいくつかあります)。
public static string OxbridgeAnd(this IEnumerable<String> collection)
{
var output = String.Empty;
var list = collection.ToList();
if (list.Count > 1)
{
var delimited = String.Join(", ", list.Take(list.Count - 1));
output = String.Concat(delimited, ", and ", list.LastOrDefault());
}
return output;
}
ユニットテストは次のとおりです。
[TestClass]
public class GrammarTest
{
[TestMethod]
public void TestThatResultContainsAnAnd()
{
var test = new List<String> { "Manchester", "Chester", "Bolton" };
var oxbridgeAnd = test.OxbridgeAnd();
Assert.IsTrue( oxbridgeAnd.Contains(", and"));
}
}
編集
このコードは、null と単一の要素を処理するようになりました。
public static string OxbridgeAnd(this IEnumerable<string> collection)
{
var output = string.Empty;
if (collection == null) return null;
var list = collection.ToList();
if (!list.Any()) return output;
if (list.Count == 1) return list.First();
var delimited = string.Join(", ", list.Take(list.Count - 1));
output = string.Concat(delimited, ", and ", list.LastOrDefault());
return output;
}
于 2014-04-18T09:27:24.127 に答える
-2
私が考えることができる最も簡単な方法は、このようなものです... print(', '.join(a[0:-1]) + ', and ' + a[-1])
a = [a, b, c, d]
print(', '.join(a[0:-1]) + ', and ' + a[-1])
a、b、c、およびd
または、カナダの構文、Oxford のコンマ、余分な波線が気に入らない場合は、次のようにします。
print(', '.join(a[0:-1]) + ' and ' + a[-1])
a、b、c、およびd
シンプルに保ちます。
于 2018-10-18T22:48:28.620 に答える