sooprise
sooprise

Reputation: 23187

If ListView Column "x" Contains "value"

This is embedded in another loop, and well, it's pretty slow. Is there a better way to do this?

for(int i=0;i< listView.Items.Count;i++)
{
    if(listView.Items[i].SubItems[3].Text == "asdf")
    {

    }
}    

Upvotes: 0

Views: 7163

Answers (2)

vapcguy
vapcguy

Reputation: 7537

In case someone runs across this using WPF, you don't get .SubItems on item when you use foreach (ListViewItem item in listView.Items). Instead, I found I could just use DataRowView and get the value of the cell that way:

foreach (DataRowView drv in listView.Items)
{
    if (drv.Row[3].ToString() == "asdf")
    {
        ...
    }
}

You do have to add a using System.Data; statement at the top of your class to use it. I found it worked in WPF, and it might in other areas (i.e. WinForms), as well.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500755

Well there's a nicer way to do it:

foreach (ListViewItem item in listView.Items)
{
    if (item.SubItems[3].Text == "asdf")
    {
         ...
    }
}

Or you could use LINQ:

var query = listView.Items
                    .Cast<ListViewItem>()
                    .Where(item => item.SubItems[3].Text == "asdf");
foreach (var item in query)
{
    ...
}

I doubt that that will be faster though...

Does your outer loop change the listView? If not, could you do the query once and reuse the results in the outer loop?

Upvotes: 3

Related Questions