无法将SelectedObjectCollection转换为ObjectCollection

本文关键字:ObjectCollection 转换 SelectedObjectCollection | 更新日期: 2023-09-27 18:16:47

我试图从ListBox中获得所有元素的列表,如果没有或其中一个项目被选中,或者如果选择的项目列表超过1个。我已经写了这样的代码,但它不编译:

    ListBox.ObjectCollection listBoXElemetsCollection;
    //loading of all/selected XMLs to the XPathDocList
    if (listBoxXmlFilesReference.SelectedIndices.Count < 2)
    {
        listBoXElemetsCollection = new ListBox.ObjectCollection(listBoxXmlFilesReference);
    }
    else
    {
        listBoXElemetsCollection = new ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
    }

因此,为了使这段代码工作,我需要使用类似ListBox.SelectedObjectCollection listBoxSelectedElementsCollection;的东西,而我不想使用它,因为我想在foreach中使用它:

            foreach (string fileName in listBoXElemetsCollection)
            {
            //...
            }

无法将SelectedObjectCollection转换为ObjectCollection

如果不需要的话,我将简单地这样做一点,而不是与ListBox ObjectCollections混淆。既然你想在ListBox上以字符串形式迭代项,为什么不使用List并按照如下方式加载列表:

List<string> listItems;
if (listBoxXmlFilesReference.SelectedIndices.Count < 2) {
    listItems = listBoxXmlFilesReference.Items.Cast<string>().ToList();
} else {
    listItems = listBoxXmlFilesReference.SelectedItems.Cast<string>().ToList();
}
foreach (string filename in listItems) {
    // ..
}

需要将SelectedObjectCollection转换为object[]数组

ListBox.SelectedObjectCollection sel = new 
                     ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
ListBox.ObjectCollection col = new 
                     ListBox.ObjectCollection(listBoxXmlFilesReference,
                         sel.OfType<object>().ToArray());

我可以看到你想做什么,它不编译,因为类型ListBox.ObjectCollection是不一样的ListBox.SelectedObjectCollection -即使在你的情况下,他们是列表,包含字符串类本身是不同的,因此编译错误。

假设列表框中的项是字符串,你可以这样做:

var items = listBoXElemetsCollection.Items.OfType<string>();
if (listBoXElemetsCollection .SelectedIndices.Count >= 2)
      items = listBoXElemetsCollection.SelectedItems.OfType<string>();      
foreach(var item in items)
            //do stuff
相关文章:
  • 没有找到相关文章