Search code examples
c#foreachmessagebox

Define single messageBox with various strings in a list, using foreach loop, possible?


I have various strings in a var set

var linhas = new[] { line8, line9, line10}

I wanna display them all in a single messagebox, but! I don't wanna display those who are empty, so i'm using the following

foreach (var l in linhas)
    if (l != null)
    {
        MessageBox.Show(l);
    }

But it only shows one message at a time, as predicted. Is it possible somehow to remove the null lines from a list, and display only those other than null in a single MessageBox?

MessageBox.Show(linenotnull8 + "\n" + linenotnull10);

Solution

  • Using the following, you can filter out null strings, then use String.Join to create a single string from the remaining strings in linhas, separating each string with a carriage return.

    MessageBox.Show(String.Join(Environment.NewLine, linhas.Where(x => x != null)));
    

    Side note... I used Environment.NewLine instead of '\n' because it will use the correct line feed character depending on the environment you're running in (Windows vs Unix).

    A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.