Steve Fallows Steve Fallows - 1 month ago 12
C# Question

How to convert SelectedListViewItemCollection to ListViewItemCollection

I'm trying to write a simple routine to process a list of items in a ListView and be able to handle all the items or the selected ones only. I expected this to work:

private void PurgeListOfStudies(ListView.ListViewItemCollection lvic)
{
/// process items in the list...
}


and then call it like this:

PurgeListOfStudies(myStudiesPageCurrent.ListView.Items);


or this

PurgeListOfStudies(myStudiesPageCurrent.ListView.SelectedItems);


However, the two lists have different and unrelated types,
ListViewItemCollection
and
SelectedListViewItemCollection
respectively.

I've tried changing the type of the parameter to
object
,
ICollection<ListViewItem>
and several other things. But since the types seem to be completely unrelated everything fails either at compile time or at runtime during a cast.

This all seems odd to me since these are obviously the same type in reality (a list of
ListViewItem
s).

Am I missing something here?

Answer

Use the MSDN documentation.

As you can see, both classes implement the interfaces: IList, ICollection, and IEnumerable. You should be able to use any of those as a common interface.

Note these are not the Generic versions (i.e. IEnumerable<T>)). You'll have to enumerate over the collection and manually cast them to your desired object type.

private void PurgeListOfStudies(IEnumerable items)
{
    foreach(MyType currentItem in items) //implicit casting to desired type
    {
        // process current item in the list...
    }
}