简体   繁体   English

c#循环比较

[英]c# loop comparisons

I use comboboxes a lot. 我经常使用组合框。 I often loop through them to find a match based upon the SelectedValue, for example... 我经常循环遍历它们以找到基于SelectedValue的匹配,例如......

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

a) am I missing some much quicker option! a)我错过了一些更快捷的选择!
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? b)如果我的比较是针对一个整数,那么声明一个字符串并将其设置为等于integer.ToString(),或者如果我只是(在上面的例子中)使用了B1ID.ToString(),那么编译器会优化它对我来说?
c) or are string comparisons so slow that I'd be better off parsing (or casting) the SelectedValue to an integer? c)或字符串比较是如此之慢以至于我最好将SelectedValue解析(或转换)为整数?

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: 这是来自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.) (请注意,此代码段首先查找集合中的数据,然后设置SelectedIndex值。)

cmbCompany.SelectedValue = B1ID应该做的伎俩 - 不是吗?

a) Maybe, but I'll let others answer that part. a)也许,但我会让其他人回答这一部分。

b) The compiler doesn't seem likely to hoist the ToString out of the loop. b)编译器似乎不太可能将ToString提升出循环。

c) Definitely slower to reparse each value. c)重新分析每个值肯定要慢一些。 Better to compare strings. 更好地比较字符串。

a/b) Have you tried using FindString ? a / b)你尝试过使用FindString吗? The method basically looks for something that *starts with (there is an equivelent one for Find exact). 该方法基本上寻找*以*开头的东西(对于Find exact有一个等效的东西)。

Or you could search the "items" and do FindByValue 或者您可以搜索“项目”并执行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) c)内置方法会更快,并且使用本机类型(也就是说它的构建成本更高,然后比较)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM