Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use LINQ on ListView.SelectedItems?

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?

like image 789
Joan Venge Avatar asked Jul 27 '09 18:07

Joan Venge


3 Answers

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(...)
like image 91
JaredPar Avatar answered Oct 21 '22 07:10

JaredPar


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( ... );
like image 28
LBushkin Avatar answered Oct 21 '22 08:10

LBushkin


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.

like image 37
Richard Berg Avatar answered Oct 21 '22 06:10

Richard Berg