Casting a ListBox.SelectedObjectCollection to a Li

2020-04-14 07:05发布

问题:

Is it possible to cast a ListBox.SelectedObjectCollection to a ListBox.ObjectCollection in C#? If so, how would I go about it?

回答1:

I have a function that accepts List<string>.

I can pass both SelectedItems and Items by casting them.

Try this:

SelectedItems.Cast<string>().ToList()
Items.Cast<string>().ToList()

<string> could be replaced with some other object type.



回答2:

This is not possible.

Instead, you should use an IList.
Both of these types implement IList, so you can pass either one as an IList without any explicit casting.

If you really wanted to, you could create a new ListBox.ObjectCollection and add the items from the SelectedObjectCollection.



回答3:

Here is my answer: it is working for me.

System.Windows.Forms.ListBox.SelectedObjectCollection lst  =this.lstImage.SelectedItems;
List<string> selectedItems = new List<string>();

foreach (object obj in lst)
{
    selectedItems.Add(obj.ToString());
}


回答4:

  List<YourDataType> YourDataTypeList = new List<YourDataType>();
  for (int i = 0; i < lbVectors.SelectedItems.Count; i++)
   {
        YourDataType v = lbVectors.SelectedItems[i] as YourDataType;
        YourDataTypeList .Add(v);
    }  


回答5:

This is my answer I used to convert Checked list box to list box

CheckedListBox.CheckedItemCollection s= checkedListBox1.CheckedItems;

        List<object> ns = new List<object>();

        foreach (object ob in s)
        {
            ns.Add(ob);
        }

        listBox1.Items.AddRange(ns.ToArray());