Joan Venge
Joan Venge

Reputation: 331280

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?

Upvotes: 10

Views: 5318

Answers (3)

LBushkin
LBushkin

Reputation: 131776

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( ... );

Upvotes: 5

Richard Berg
Richard Berg

Reputation: 20782

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.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755179

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(...)

Upvotes: 28

Related Questions