How do I put the contents of a list in a single MessageBox?

前端 未结 5 1134
陌清茗
陌清茗 2020-12-28 20:19

Basically, I have a list with multiple items in it and I want a single message box to display them all.

The closest I have got is a message box for each item (using

相关标签:
5条回答
  • 2020-12-28 20:43

    Just for fun and in case you need to do something like that with non-string collections one time - a LINQ version using Aggregate, which is the closest to your example syntax. Don't use it here, do indeed use String.Join in this case, but keep in mind that you have something in LINQ that can do what you need.

    MessageBox.Show("List contains: " + 
       list.Aggregate((str,val) => str + Environment.NewLine + val);
    

    EDIT: also, like Martinho Fernandes pointed out, it's better to use the StringBuilder class in cases like that, so:

    MessageBox.Show("List contains: " + list.Aggregate(new StringBuilder(), 
                                                   (sb,val) => sb.AppendLine(val), 
                                                   sb => sb.ToString()));
    
    0 讨论(0)
  • 2020-12-28 20:43

    simply you need to make a for loop for example:

     string total ="";
        for(int i =0; i<x.count ;i++)
       {
         total =total+x[i] +"\n";
       }
       MessageBox.Show(total);
    
    0 讨论(0)
  • 2020-12-28 20:46

    If you have .Net 4.0

    string s = String.Join(",", list);
    

    If you don't but have 3.5

    string s = String.Join(",", list.ToArray());
    
    0 讨论(0)
  • 2020-12-28 20:50

    You can join everything into a single string with string.Join:

    var message = string.Join(Environment.NewLine, list);
    MessageBox.Show(message);
    

    However, if you don't have access to .NET 4, you don't have that overload that takes an IEnumerable<string>. You will have to fallback on the one that takes an array:

    var message = string.Join(Environment.NewLine, list.ToArray());
    MessageBox.Show(message);
    
    0 讨论(0)
  • 2020-12-28 21:03

    You can also use Stringbuilder:

    StringBuilder builder = new StringBuilder();
    
    
    foreach(string str in list)
    {
        builder.Append(str.ToString()).AppendLine();  
    }           
    
    Messagebox.Show(builder.ToString());
    

    Regards

    0 讨论(0)
提交回复
热议问题