加入分离器以供显示的项目列表

编程入门 行业动态 更新时间:2024-10-26 08:22:12
本文介绍了加入分离器以供显示的项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有我想要显示在C#它们之间的分隔符的项目清单。使用普通的迭代器我最终会在开始一个额外的分离器或结尾:

I have a list of items that I wish to display with a separator between them in C#. Using a normal iterator I would end up with an extra separator at the beginning or the end:

string[] sa = {"one", "two", "three", "four"}; string ns = ""; foreach(string s in sa) { ns += s + " * "; } // ns has a trailing *: // one * two * three * four *

现在我可以用一个for循环,像这样解决这个问题:

Now I can solve this using a for loop like so:

ns = ""; for(int i=0; i<sa.Length; i++) { ns += sa[i]; if(i != sa.Length-1) ns += " * "; } // this works: // one * two * three * four

虽然第二个解决方案可它看起来并不很优雅。有没有更好的方式来做到这一点?

Although the second solution works it doesn't look very elegant. Is there a better way to do this?

推荐答案

您需要内置的 的string.join 方式:

You need the built-in String.Join method:

string ns = string.Join(" * ", sa);

如果你想与其他集合类型也这样做,那么你仍然可以使用的string.join 如果你创建一个数组首先使用LINQ的的 的ToArray 方式:

If you want to do the same with other collection types, then you can still use String.Join if you create an array first using LINQ's ToArray method:

string ns = string.Join(" * ", test.ToArray());

更多推荐

加入分离器以供显示的项目列表

本文发布于:2023-11-25 07:30:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628866.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:以供   分离器   项目   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!