我知道我可以找到出路,但我想知道是否有更简洁的解决方案。总是有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 回答
8
此版本枚举值一次并使用任意数量的值:
public static string JoinAnd<T>(string separator, string sepLast, IEnumerable<T> values)
{
var sb = new StringBuilder();
var enumerator = values.GetEnumerator();
if (enumerator.MoveNext())
{
sb.Append(enumerator.Current);
}
object obj = null;
if (enumerator.MoveNext())
{
obj = enumerator.Current;
}
while (enumerator.MoveNext())
{
sb.Append(separator);
sb.Append(obj);
obj = enumerator.Current;
}
if (obj != null)
{
sb.Append(sepLast);
sb.Append(obj);
}
return sb.ToString();
}
于 2017-07-03T13:20:14.417 回答
4
此版本仅枚举值一次,并适用于任意数量的值。
( @Grastveit 的改进答案)
我将其转换为扩展方法并添加了一些单元测试。添加了一些空检查。我还修复了一个错误,如果values
集合中的一个项目包含null
,并且它是最后一个,它将被完全跳过。String.Join()
这与现在在 .NET Framework 中的行为方式不相符。
#region Usings
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace MyHelpers
{
public static class StringJoinExtensions
{
public static string JoinAnd<T>(this IEnumerable<T> values,
string separator, string lastSeparator = null)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (separator == null)
throw new ArgumentNullException(nameof(separator));
var sb = new StringBuilder();
var enumerator = values.GetEnumerator();
if (enumerator.MoveNext())
sb.Append(enumerator.Current);
bool objectIsSet = false;
object obj = null;
if (enumerator.MoveNext())
{
obj = enumerator.Current;
objectIsSet = true;
}
while (enumerator.MoveNext())
{
sb.Append(separator);
sb.Append(obj);
obj = enumerator.Current;
objectIsSet = true;
}
if (objectIsSet)
{
sb.Append(lastSeparator ?? separator);
sb.Append(obj);
}
return sb.ToString();
}
}
}
这是一些单元测试
#region Usings
using MyHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
#endregion
namespace UnitTests
{
[TestClass]
public class StringJoinExtensionsFixture
{
[DataTestMethod]
[DataRow("", "", null, null)]
[DataRow("1", "1", null, null)]
[DataRow("1 and 2", "1", "2", null)]
[DataRow("1, 2 and 3", "1", "2", "3")]
[DataRow(", 2 and 3", "", "2", "3")]
public void ReturnsCorrectResults(string expectedResult,
string string1, string string2, string string3)
{
var input = new[] { string1, string2, string3 }
.Where(r => r != null);
string actualResult = input.JoinAnd(", ", " and ");
Assert.AreEqual(expectedResult, actualResult);
}
[TestMethod]
public void ThrowsIfArgumentNulls()
{
string[] values = default;
Assert.ThrowsException<ArgumentNullException>(() =>
StringJoinExtensions.JoinAnd(values, ", ", " and "));
Assert.ThrowsException<ArgumentNullException>(() =>
StringJoinExtensions.JoinAnd(new[] { "1", "2" }, null,
" and "));
}
[TestMethod]
public void LastSeparatorCanBeNull()
{
Assert.AreEqual("1, 2", new[] { "1", "2" }
.JoinAnd(", ", null),
"lastSeparator is set to null explicitly");
Assert.AreEqual("1, 2", new[] { "1", "2" }
.JoinAnd(", "),
"lastSeparator argument is not specified");
}
[TestMethod]
public void SeparatorsCanBeEmpty()
{
Assert.AreEqual("1,2", StringJoinExtensions.JoinAnd(
new[] { "1", "2" }, "", ","), "separator is empty");
Assert.AreEqual("12", StringJoinExtensions.JoinAnd(
new[] { "1", "2" }, ",", ""), "last separator is empty");
Assert.AreEqual("12", StringJoinExtensions.JoinAnd(
new[] { "1", "2" }, "", ""), "both separators are empty");
}
[TestMethod]
public void ValuesCanBeNullOrEmpty()
{
Assert.AreEqual("-2", StringJoinExtensions.JoinAnd(
new[] { "", "2" }, "+", "-"), "1st value is empty");
Assert.AreEqual("1-", StringJoinExtensions.JoinAnd(
new[] { "1", "" }, "+", "-"), "2nd value is empty");
Assert.AreEqual("1+2-", StringJoinExtensions.JoinAnd(
new[] { "1", "2", "" }, "+", "-"), "3rd value is empty");
Assert.AreEqual("-2", StringJoinExtensions.JoinAnd(
new[] { null, "2" }, "+", "-"), "1st value is null");
Assert.AreEqual("1-", StringJoinExtensions.JoinAnd(
new[] { "1", null }, "+", "-"), "2nd value is null");
Assert.AreEqual("1+2-", StringJoinExtensions.JoinAnd(
new[] { "1", "2", null }, "+", "-"), "3rd value is null");
}
}
}
于 2018-04-27T19:06:44.893 回答
-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
或者,如果您不喜欢加拿大语法、牛津逗号和额外的花体:
print(', '.join(a[0:-1]) + ' and ' + a[-1])
a、b、c 和 d
保持简单。
于 2018-10-18T22:48:28.620 回答