views:

321

answers:

3

I am trying to do use .Select extension method on ListView.SelectedItems which is SelectedListViewItemCollection, but .Select doesn't show up in intellisense.

I can use foreach on SelectedListViewItemCollection, so it must have implemented IEnumerable. I just checked on MSDN, and it certainly does. Then why can't the LINQ extension methods be used on it?

+11  A: 

The reason why is that SelectedItems is typed to a collection which implements IEnumerable. The Select extension method is bound to IEnumerable<T>. Hence it won't work with SelectedItems.

The workaround is to use the .Cast extension method to get it to the appropriate type and it should show up

ListView.SelectedItems.Cast<SomeType>.Select(...)
JaredPar
Thanks Jared. .
Joan Venge
It's gonna be ListViewItem as type, right?
Joan Venge
@Joan, I'm actually not sure. I believe it's the underlying item and not ListViewItem. I can't find the answer in the documentation.
JaredPar
@Joan, yes you are correct, it will return a ListViewItem
JaredPar
Thanks Jared. Just wanted to make sure.
Joan Venge
+4  A: 

It implements IEnumerable, not IEnumerable<T> - all LINQ queries are built around the generic IEnumerable<T> interface to allow type safety and generic inference - particularly when dealing with anonymous types.

You can use the following instead:

myListView.SelectedItems.Cast<ListViewItem>.Select( ... );
LBushkin
Thanks LBushkin.
Joan Venge
+2  A: 

Do you have "using System.Linq" at the top of your file?

Is it a strongly typed generic collection? If not, you'll need to use the Cast<> extension method.

Richard Berg