加入分离器以供显示的项目列表 [英] Adding a separator to a list of items for display

查看:120
本文介绍了加入分离器以供显示的项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要显示在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());

这篇关于加入分离器以供显示的项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆