我有我想要显示在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());更多推荐
加入分离器以供显示的项目列表
发布评论