简体   繁体   English

如何将ListBox.items转换为c#中的数组集合字符串

[英]How to convert ListBox.items to string of array collection in c#

I have bound array as datasource for ListBox . 我已将数组绑定为ListBox的数据源。 Now i need to convert listbox.Items to string of array collection. 现在我需要将listbox.Items转换为数组集合的字符串。

foreach (string s1 in listBoxPart.Items)
{
   clist.Add(s1);
}

here clist is string list, so how can i add ListBox.items to clist? 这里clist是字符串列表,那么如何将ListBox.items添加到clist?

You can project any string contained inside Items using OfType . 您可以使用OfType投影Items包含的任何string This means that any element inside the ObjectCollection which is actually a string , would be selected: 这意味着将选择ObjectCollection中实际为string任何元素:

string[] clist = listBoxPart.Items.OfType<string>().ToArray();
for (int a = 0; a < listBoxPart.Items.Count; a++)
    clist.Add(listBoxPart.Items[a].ToString());

This should work if the items saved in the list are actualy strings, if they are objects you need to cast them and then use whatever you need to get strings out of them 如果列表中保存的项目是实际字符串,如果它们是您需要投射它们的对象,然后使用您需要的任何东西从它们中获取字符串,这应该有用

Just create a list of strings and then add the item.toString() to it. 只需创建一个字符串列表,然后将item.toString()添加到它。

var list = new List<string>();

foreach (var item in Listbox1.Items)
{
    list.Add(item.ToString());
}

If the array which is the datasource contains strings: 如果作为数据源的数组包含字符串:

clist.AddRange(listBoxPart.Items.Cast<string>());

or if the DataSource is a String[] or List<string> : 或者如果DataSourceString[]List<string>

clist.AddRange((Ilist<string>)listBoxPart.DataSource);

if this is actually ASP.NET: 如果这实际上是ASP.NET:

clist.AddRange(listBoxPart.Items.Cast<ListItem>().Select(li => li.Text));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM