如何将字符串列表以及每个值之间的逗号连接在一起?

时间:2018-12-09 10:36:57

标签: c# .net string linq

我需要有关此代码的帮助。我想像这样在foreach循环中拆分单词,但我不想在最后一个单词之后添加,。有什么建议吗?

var listOtherWords = (from o in Words
                      where !o.ToUpper().StartsWith("A")
                      where !o.ToUpper().StartsWith("B")
                      where !o.ToUpper().StartsWith("C")
                      select o).ToList();

Console.WriteLine();
Console.Write("Other Words: ");

foreach (string o in lisOtherWords)
{
    Console.Write(o + " ,");
}

Console.ReadLine();

3 个答案:

答案 0 :(得分:2)

您可以使用String.Join方法:

Console.Write(string.Join(" ,", listOtherWords));

或使用\b \b"

foreach (string o in listOtherWords)
{
    Console.Write(o + " ,");
}

Console.Write("\b \b");

它将插入符号移回,然后写入一个空格字符,该字符会覆盖最后一个字符,然后再次将插入符号向前移。

答案 1 :(得分:1)

使用string.Join会更好:

Console.Write(string.Join(" ,", lisOtherWords));

答案 2 :(得分:0)

除了.travis之外,您还可以使用Join方法:

Aggregate

唯一的区别是您将能够在循环中添加其他逻辑。例如:

string line = listOtherWords.Aggregate((a,b) => $"{a} ,{b}");