ListView Iterations

If there is need to iterate through ListView items, I often see following code:

foreach (var item in listView1.Items) {
var itemX = (ListViewItem)item;
//do something with itemX
}

Unfortunately C# compiler is not smart enough to notice that item is actually ListViewItem so it keeps it as Object. And thus we need to cast it to our desired type.

Well, actually there is no need to do this. One just needs to remember live before implicit typing with var came:

foreach (ListViewItem item in listView1.Items) {
//do something with item
}

This still works and it definitely looks nicer.

Leave a Reply

Your email address will not be published. Required fields are marked *