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

前端 未结 5 1162
陌清茗
陌清茗 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()));
    

提交回复
热议问题