ListBox(多选)选中的索引

ListBox (multiselect) selected indexes

我有一个支持 Multi-SelectListBox,我需要一种方法来检索所有选定的索引作为 List<int>

例如:

Listbox
{
    item 1 - not selected
    item 2 - selected
    item 3 - selected
    item 4 - not selected
}

因此所选索引 List<int> 将如下所示:

List<int>() { 1, 2 };

试试这个:

List<int> list = new List<int>();

foreach (var item in listBox1.SelectedItems)
{
   list.Add(listBox1.Items.IndexOf(item));// Add selected indexes to the List<int>
}

或者使用 linq:

List<int> list = (from object obj in listBox1.SelectedItems 
                  select listBox1.Items.IndexOf(obj)).ToList();