优化C#中的字符串比较
我在 asp.net 按钮上有以下代码,单击
if(str == ipaddr1 || ipaddr2 || ipaddr3 || ipaddr4 || ipaddr5 || ipaddr6 || ipaddr7)
// do this
else
//cancel click event
如何优化这段代码?
更新:向大家道歉!我并不是想将它与文字字符串 ipaddr 进行比较。我的意思是将其与 ipaddr1、ipaddr2 所持有的值进行比较,依此类推
I have the following code on an asp.net button click
if(str == ipaddr1 || ipaddr2 || ipaddr3 || ipaddr4 || ipaddr5 || ipaddr6 || ipaddr7)
// do this
else
//cancel click event
How can I optimize this piece of code?
Update: Apologies everyone! I did not mean to compare it with the literal string ipaddr. I mean to compare it to the value ipaddr1, ipaddr2 holds and so on
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
替换为:
针对可读性进行优化,不一定是针对性能进行优化。
replace with:
Optimised for readability not necessarily performance.
HashSet
是检查包含的最佳容器:对于任何类型:
Was:
变成:
StringComparison.Ordinal
或StringComparison.OrdinalIgnoreCase
非常对性能很重要。HashSet<T>
is the best container to check containing:For any type:
Was:
Become:
StringComparison.Ordinal
orStringComparison.OrdinalIgnoreCase
are very important for performance.供您参考
,您的原始代码甚至无法编译。 所以
需要替换成this才能编译
原来的代码其实比你想象的还要繁琐。
更新
根据您更新的问题,最好的选择是将字符串变量放入名为的
List
中,例如ipaddr
。然后要查看是否包含字符串str
,只需执行以下操作:What about
For your information, your original code does not even compile. This
Needs to be replaced with this to compile
So the original code is actually even more tedious than you thought.
UPDATE
According to your updated question, the best option is to put your string variables into a
List<string>
called, for exampleipaddr
. Then to see if the stringstr
is included, simply do this:我会做类似的事情:
编辑:
更新后,我会做类似的事情:
为了获得更好的性能,请考虑使用
HashSet
而不是数组,特别是如果有效字符串列表不会改变。I would do something like:
Edit:
After your update, I would do something like:
For better performance, consider using a
HashSet<string>
instead of an array, especially if the list of valid strings doesn't change.更具可读性和更高的性能将是:(
尽管,不可否认的是非常冗长......)
Both more readable, and more performant would be:
(although, admittedly massively verbose...)
我会做一个
I would do a