1

I need help with this code. I want to split words in foreach loop like this but I don't want a , after the last word. Any suggestions?

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();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 3
    Possible duplicate of [Concat all strings inside a List using LINQ](https://stackoverflow.com/questions/559415/concat-all-strings-inside-a-liststring-using-linq) – mjwills Dec 09 '18 at 11:01

3 Answers3

5

You can either use String.Join method:

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

Or use \b \b":

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

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

It moves the caret back, then writes a whitespace character that overwrites the last character and moves the caret forward again.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

you would be better off using string.Join:

Console.Write(string.Join(" ,", lisOtherWords));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Other than Join You can also use Aggregate method:

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

The only difference is that you will be able to add additional logic to your loop. e.g:

string line = listOtherWords.Aggregate((a,b) =>
{
    if(...) ...
    return $"{a} ,{b}";
});
Bizhan
  • 16,157
  • 9
  • 63
  • 101