如何将 2 个 listBox 中的项目添加到一个 listBox?
例如:listBox1 包含 Hello listBox2 包含 World!因此,如果在 listbox3 中单击 button1 将显示 Hello World!并排,但不在新行中
你好
世界!
private void button2_Click(object sender, EventArgs e)
{
listBox3.Items.Add(listBox1.Items + listBox2.Items);
}
既然你说;
listBox1 中的所有单词都将是 + 与 listBox2 在 listBox3
private void button2_Click(object sender, EventArgs e)
{
string s = "";
for(int i = 0; i < listBox1.Items.Count; i++)
{
s += listBox1.Items[i].ToString() + " ";
}
for(int j = 0; j < listBox2.Items.Count; j++)
{
s += listBox2.Items[j].ToString() + " ";
}
listBox3.Items.Add(s.Trim());
}
但例如:我的 listBox1 包含 Hello Hi Sup,而我的 listBox2 包含 World!点击 listBox3 后会变成 Hello Hi Sup World!而不是你好世界!你好世界!苏世界!
如果你想作为你的一个项目listBox3,你可以使用上面的解决方案。如果你想在你的 4 个项目中listBox3,你可以像这样使用它;
private void button2_Click(object sender, EventArgs e)
{
for(int i = 0; i < listBox1.Items.Count; i++)
{
listBox3.Items.Add(listBox1.Items[i].ToString());
}
for(int j = 0; j < listBox2.Items.Count; j++)
{
listBox3.Items.Add(listBox2.Items[j].ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
listBox3.Items.Add(string.Format("{0} {1}", listBox1.Items[0].ToString().Trim() , listBox2.Items[0].ToString().Trim()));
}
如果您需要两个列表框中的所有单词到一个列表框中
private void button2_Click(object sender, EventArgs e)
{
listBox3.Items.Add( string.Format("{0} {1}", string.Join(" ", listBox1.Items.Cast<string>()) , string.Join(" ", listBox2.Items.Cast<string>())));
}
更新 :
private void button2_Click(object sender, EventArgs e)
{
listBox3.Items.AddRange(listBox1.Items.Cast<string>().Zip(listBox2.Items.Cast<string>(), (first, second) => first + " " + second).ToArray());
}