且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ名单判处格式(插入逗号和放大器;"和")

更新时间:2023-01-19 16:41:25

为什么LINQ的?

StringBuilder sb = new StringBuilder();

for(int i=0;i<k.Count();i++)
{
   sb.Append(String.Format("{0}:{1}", k[i].ID, k[i].Name);
   if(i + 2 < k.Count())
      sb.Append(", ");
   else if(i + 1 < k.Count())
      sb.Append(" and ");
}

真的,所有的LINQ可以让你做的是隐藏循环。

Really, all Linq will let you do is hide the loop.

此外,还要确保你做或不想在牛津逗号,这种算法将不插入一个,而是一个小的变化会(追加逗号和除最后每个元素之后的空间,并且还追加和下一个到最后一个)。

Also, make sure you do or do not want the "Oxford Comma"; this algorithm will not insert one, but a small change will (append the comma and space after every element except the last, and also append "and " after the next-to-last).