如何列出一份看起来自然的清单
本文关键字:自然 看起来 一份 何列出 | 更新日期: 2023-09-27 18:24:19
所谓自然外观,我的意思是:
第1项、第2项、第3项和第4项。
我知道你可以用string.Join
做一个逗号分隔的列表,就像一样
第1项、第2项、第3项、第4项
但是你怎么能列出这样的清单呢?我有一个基本的解决方案:
int countMinusTwo = theEnumerable.Count() - 2;
string.Join(",", theEnumerable.Take(countMinusTwo)) + "and "
+ theEnumerable.Skip(countMinusTwo).First();
但我很确定有更好(更有效)的方法可以做到。有人吗?谢谢
您应该计算一次大小并将其存储在变量中。否则,每次都会执行查询(如果不是集合)。此外,如果您想要最后一项,Last
更具可读性。
string result;
int count = items.Count();
if(count <= 1)
result = string.Join("", items);
else
{
result = string.Format("{0} and {1}"
, string.Join(", ", items.Take(counter - 1))
, items.Last());
}
如果可读性不那么重要,并且序列可能相当大:
var builder = new StringBuilder();
int count = items.Count();
int pos = 0;
foreach (var item in items)
{
pos++;
bool isLast = pos == count;
bool nextIsLast = pos == count -1;
if (isLast)
builder.Append(item);
else if(nextIsLast)
builder.Append(item).Append(" and ");
else
builder.Append(item).Append(", ");
}
string result = builder.ToString();
我会使用字符串。
假设你有:
string items = "item1, item2, item3, item4";
然后你可以做:
int lastIndexOf = items.LastIndexOf(",");
items = items.Remove(lastIndexOf);
items = items.Insert(lastIndexOf, " and");