Graham
Graham

Reputation: 25

c# loop comparisons

I use comboboxes a lot. I often loop through them to find a match based upon the SelectedValue, for example...

while(cmbCompany.SelectedValue.ToString()!=B1ID)
{ 
    cmbCompany.SelectedIndex++; 
}

a) am I missing some much quicker option!
b) if my comparison was against an integer, is there any benefit in declaring a string and setting that equal to the integer.ToString(), or if I just (in my example above) used B1ID.ToString() would the compiler optimise it for me?
c) or are string comparisons so slow that I'd be better off parsing (or casting) the SelectedValue to an integer?

Upvotes: 2

Views: 345

Answers (4)

Paul Sasik
Paul Sasik

Reputation: 81429

The most confounding part of your algorithm is that you're incrementing the index with every comparison. This is very inefficient because you actually change the selection with every test which also fires events (if you have them wired) and potentially dangerous because reacting to the selection change event every time will make your logic unnecessarily complex.

There are a number of other ways. Here is a better (though rough) code sample from MSDN:

int index = comboBox1.FindString(textBox2.Text);
comboBox1.SelectedIndex = index;

(Notice that this code snippet looks for the data in the collection first and then sets the SelectedIndex value.)

Upvotes: 8

Nix
Nix

Reputation: 58522

a/b) Have you tried using FindString? The method basically looks for something that *starts with (there is an equivelent one for Find exact).

Or you could search the "items" and do FindByValue

  cmbCompany.Items.FindByValue

c) Built in methods will be faster, as well as using native types (aka its more costly to cast and then compare)

Upvotes: 0

Steven Sudit
Steven Sudit

Reputation: 19620

a) Maybe, but I'll let others answer that part.

b) The compiler doesn't seem likely to hoist the ToString out of the loop.

c) Definitely slower to reparse each value. Better to compare strings.

Upvotes: 0

Will A
Will A

Reputation: 24988

cmbCompany.SelectedValue = B1ID ought to do the trick - does it not?

Upvotes: 1

Related Questions