将分隔符添加到要显示的项目列表中

Guy*_*Guy 3 c# algorithm

我有一个项目列表,我想在C#中用它们之间的分隔符显示.使用普通的迭代器,我会在开头或结尾处添加一个额外的分隔符:

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

现在我可以使用for循环来解决这个问题:

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

虽然第二种解决方案有效,但看起来并不优雅.有一个更好的方法吗?

Luk*_*keH 19

您需要内置String.Join方法:

string ns = string.Join(" * ", sa);
Run Code Online (Sandbox Code Playgroud)

如果你想对其他集合类型做同样的事情,那么String.Join如果你首先使用LINQ的ToArray方法创建一个数组,你仍然可以使用:

string ns = string.Join(" * ", test.ToArray());
Run Code Online (Sandbox Code Playgroud)