Steve Fallows Steve Fallows - 1 year ago 171
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:


or this


However, the two lists have different and unrelated types,

I've tried changing the type of the parameter to
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

Am I missing something here?

Answer Source

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...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download