2

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();
1

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

you would be better off using string.Join:

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

Comments

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}";
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.