riqitang
riqitang

Reputation: 3371

Generic List of ListViewItems

Sorry for the title, I couldn't think of a more descriptive/succinct way to convey my problem.

My problem is that I have a function which operates on a collection of ListViewItems via a foreach-loop, and the list of items it will operate on depends on a boolean parameter to the function, call it bSelected.

If this is true, I want to use the SelectedItems from my list view, otherwise I want to use the Items from the list view.

I'm having trouble determining what this object representing the list of items should be, or how to get it. I've tried a couple different approaches (Note the ListView is called lvList):

IList<ListViewItem> listItems = 
  ( bSelected ? (IList<ListViewItem>)lvList.SelectedItems 
              : (IList<ListViewItem>)lvList.Items );
foreach ( ListViewItem lvi in listItems ) { ... }

and

IEnumerator<ListViewItem> listEnumerator = 
  ( bSelected ? (IEnumerator<ListViewItem>)lvList.SelectedItems.GetEnumerator() 
              : (IEnumerator<ListViewItem>)lvList.Items.GetEnumerator() );
while ( listEnumerator.MoveNext() ) { ... }

I've tried other solutions of a similar ilk, but I get run-time errors having to do with type conversions applied to the SelectedItems.

I know that there's got to be a way, since using foreach loops directly on one list or the other works, i.e.:

foreach ( ListViewItem lvi in lvList.SelectedItems ) { ... }

and

foreach ( ListViewItem lvi in lvList.Items ) { ... }

I don't have much C# experience, so help is appreciated.

Upvotes: 0

Views: 1613

Answers (4)

alex
alex

Reputation: 12654

Try using untyped untyped IEnumerable:

IEnumerable listEnumerable = 
  ( bSelected ? lvList.SelectedItems 
              : lvList.Items);
foreach ( ListViewItem lvi in listEnumerable ) { ... }

Upvotes: 1

Jens Kloster
Jens Kloster

Reputation: 11277

You could force it to be a strongly typed List like this:

List<ListViewItem> listItems = 
  ( bSelected ? lvList.SelectedItems.Cast<ListViewItem>().ToList()
              : lvList.Items.Cast<ListViewItem>().ToList() );

Go here for more info on Cast

Upvotes: 1

Martin
Martin

Reputation: 16433

You can use an IList as they both implement it. Try the following:

IList listItems = 
  ( bSelected ? (IList)lvList.SelectedItems 
              : (IList)lvList.Items );
foreach ( ListViewItem lvi in listItems ) { ... }

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33511

In the documentation, it says they are of type ListViewItemCollection:

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.items.aspx

Upvotes: 0

Related Questions