基本上,我有一个包含多个项目的列表,并且我希望一个单独的消息框来显示它们所有。
我最接近的方法是为每个项目使用 foreach
显示一个消息框。
我想要的是等同于:
MessageBox.Show ("List contains:"+
Foreach (string str in list)
{ str + Environment.Newline + }
)
但是显然这样做行不通!正确的方法是什么?
string.Join
将所有内容连接成一个字符串:var message = string.Join(Environment.NewLine, list);
MessageBox.Show(message);
但是,如果您无法访问.NET 4,就没有那个接受 IEnumerable<string>
的重载。您将不得不退回到接受 数组的方法:
var message = string.Join(Environment.NewLine, list.ToArray());
MessageBox.Show(message);
string s = String.Join(",", list);
string s = String.Join(",", list.ToArray());
StringBuilder builder = new StringBuilder();
foreach(string str in list)
{
builder.Append(str.ToString()).AppendLine();
}
Messagebox.Show(builder.ToString());
问候
仅供娱乐,以及在您有一次需要使用非字符串集合的情况下 - 使用Aggregate
的LINQ版本,它是最接近您示例语法的方法。在这种情况下不要使用它,确实使用String.Join
,但请记住您在LINQ中有可以满足您需求的东西。
MessageBox.Show("List contains: " +
list.Aggregate((str,val) => str + Environment.NewLine + val);
编辑:正如Martinho Fernandes指出的那样,在这种情况下最好使用StringBuilder
类,因此:
MessageBox.Show("List contains: " + list.Aggregate(new StringBuilder(),
(sb,val) => sb.AppendLine(val),
sb => sb.ToString()));
Aggregate
,最好聚合 StringBuilder
而不是字符串:.Aggregate(new StringBuilder(), (sb,x) => sb.AppendLine(x), sb => sb.ToString());
:P - R. Martinho Fernandes你只需要编写一个for循环,例如:
string total ="";
for(int i =0; i<x.count ;i++)
{
total =total+x[i] +"\n";
}
MessageBox.Show(total);
", "
代替Enviornment.NewLine
。 - lost_in_the_source