sooprise sooprise - 1 year ago 72
C# Question

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")
{

}
}

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download