c#将选定的列表框项目复制到字符串中

Spe*_*cer 2 c# foreach listbox

我在将列表框中的选定值转换为字符串时遇到了一些问题.

列表框包含多个值,我们称之为AZ.基本上,我想将所选项目复制到一个字符串中.

var listarray = new System.Collections.ArrayList(listboxName.SelectedItems);

string myval = "";

foreach (var arr in listarray)
{
    myval = dep.ToString();
    Console.WriteLine(myval); // this shows all the selected values
}

string finalStr = "some text before the values" + myval;
Console.WriteLine(finalStr);
Run Code Online (Sandbox Code Playgroud)

我希望字符串显示"值A,B,C,D ......之前的一些文本",而是输出"值A之前的一些文本"

最后一个Console.WriteLine只显示一个值而不是所有选定的值.我已经尝试finalStrforeach循环内部添加,但这会创建多个实例,finalStr而不是只有一个具有多个数组值的字符串.

Ser*_*kiy 5

使用String.Join从items集合构建连接字符串:

string finalStr = "Some text before the values " + 
           String.Join(", ", listboxName.SelectedItems.Cast<YourItemType>());
Run Code Online (Sandbox Code Playgroud)